React Hook Form: Conditional Field Validation Based on Other Fields' Values
I'm working on a personal project and I tried several approaches but none seem to work... I'm working on a form using React Hook Form version 7.0.0 and I need to enforce conditional validation based on the values of other fields. Specifically, I have a situation where I want to ensure that if the user selects 'yes' from a radio button group, then a text input must be filled out, otherwise it can be left blank. I've set up my fields like this: ```jsx import { useForm } from 'react-hook-form'; const MyForm = () => { const { register, handleSubmit, watch, formState: { errors } } = useForm(); const watchYesNo = watch('yesNo'); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label> <input type="radio" value="yes" {...register('yesNo')} /> Yes </label> <label> <input type="radio" value="no" {...register('yesNo')} /> No </label> <input type="text" {...register('conditionalField', { required: watchYesNo === 'yes' })} /> {errors.conditionalField && <span>This field is required when Yes is selected</span>} <button type="submit">Submit</button> </form> ); }; ``` However, I'm working with a question where the validation does not seem to trigger as expected. When I select 'yes' and leave the text input blank, the form submits without any errors, which is confusing. I've verified that `watchYesNo` is updating correctly, but it seems like the validation does not take effect dynamically based on its state. I've tried using the `trigger()` function to manually trigger validation after the state changes, but I'm still getting the same behavior. Here's how I attempted to implement that: ```jsx useEffect(() => { trigger('conditionalField'); }, [watchYesNo]); ``` This doesn't appear to resolve the scenario either. What am I missing here? How can I ensure that the required validation is effectively tied to the value of the radio button? Any insights would be greatly appreciated! This is part of a larger application I'm building. What's the best practice here? Hoping someone can shed some light on this.