CodexBloom - Programming Q&A Platform

React Hook Form Validation scenarios on Conditional Fields with Next.js and TypeScript

👀 Views: 380 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-04
react typescript react-hook-form TypeScript

I recently switched to I've been banging my head against this for hours. I'm using React Hook Form (v7.0.0) in a Next.js (v12.0.0) project with TypeScript. I've set up a form that has conditional fields, and I'm working with issues with validation not triggering correctly for these fields. The form includes a dropdown that, when a specific option is selected, makes a text field required. However, even when the condition is met, the validation fails silently without showing any behavior messages. Here's a simplified version of my form: ```tsx import { useForm } from 'react-hook-form'; interface FormValues { option: string; conditionalField: string; } const MyForm = () => { const { register, handleSubmit, watch, formState: { errors } } = useForm<FormValues>(); const option = watch('option'); const onSubmit = (data: FormValues) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <select {...register('option')}> <option value="">Select an option</option> <option value="show">Show Conditional Field</option> <option value="hide">Hide Conditional Field</option> </select> {option === 'show' && ( <input {...register('conditionalField', { required: option === 'show' ? 'This field is required when "Show" is selected.' : false })} /> )} {errors.conditionalField && <p>{errors.conditionalField.message}</p>} <button type="submit">Submit</button> </form> ); }; ``` I've tried checking if the `option` value changes correctly when I select a different option, and it does. However, the validation for the `conditionalField` doesn't seem to trigger as expected when I submit the form. I've also ensured that I'm properly handling the `onSubmit` function and behavior display. Is there something I'm missing in the setup or usage of React Hook Form that could lead to this behavior? Any insights would be greatly appreciated! What are your experiences with this? I'm working on a desktop app that needs to handle this. What's the correct way to implement this?