CodexBloom - Programming Q&A Platform

React Hook Form: implementing Conditional Field Validation on Dynamic Forms

👀 Views: 86 💬 Answers: 1 📅 Created: 2025-06-10
react react-hook-form validation JavaScript

I'm working on a dynamic form using React Hook Form (version 7) where I need to conditionally validate fields based on user input... I'm dynamically adding fields based on the selection of a dropdown, but I've run into a question where the validation rules for these dynamically added fields aren't being applied correctly. The fields sometimes show the behavior messages even when they should be valid. Here's a simplified version of my form setup: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; const MyForm = () => { const { control, handleSubmit, setValue, watch } = useForm(); const selectedType = watch('type'); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="type" control={control} defaultValue="option1" render={({ field }) => ( <select {...field}> <option value="option1">Option 1</option> <option value="option2">Option 2</option> </select> )} /> {selectedType === 'option2' && ( <Controller name="dynamicField" control={control} rules={{ required: 'This field is required when Option 2 is selected.' }} render={({ field, fieldState }) => ( <div> <input {...field} /> {fieldState.behavior && <p>{fieldState.behavior.message}</p>} </div> )} /> )} <button type="submit">Submit</button> </form> ); }; ``` Despite having the validation rules in place, I sometimes see the behavior message for the dynamic field even when the input is filled correctly, especially if I switch between the options multiple times. I've tried moving the validation rules around, but that didn’t seem to have any effect. Also, I've noticed that if I leave the field empty and switch to `option1`, the behavior message for the dynamic field still continues until I refresh the page. Any suggestions on how I can properly handle this conditional validation and avoid lingering behavior messages? I'm working on a API that needs to handle this. Is there a better approach?