React Hook Form: Handling Conditional Fields with Validation in v7
I'm converting an old project and I'm working on a personal project and I'm working on a form using React Hook Form v7, and I'm trying to implement conditional fields that require validation only when specific criteria are met. For instance, I have a checkbox that, when checked, should require a text input to be filled out. However, I'm working with an scenario where the validation for the text input isn't being triggered correctly based on the checkbox state. Hereβs a simplified version of my code: ```javascript import React from 'react'; import { useForm } from 'react-hook-form'; const MyForm = () => { const { register, handleSubmit, watch, formState: { errors } } = useForm(); const watchCheckbox = watch('checkbox'); // Watch the checkbox state const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label> <input type="checkbox" {...register('checkbox')} /> Require additional input </label> <label> Additional Input: <input type="text" {...register('additionalInput', { required: watchCheckbox, validate: value => watchCheckbox && value !== '' || 'This field is required' })} /> {errors.additionalInput && <span>{errors.additionalInput.message}</span>} </label> <button type="submit">Submit</button> </form> ); }; export default MyForm; ``` The intention is that if the checkbox is checked, the additional input becomes required. However, even when the checkbox is unchecked, the validation seems to be firing incorrectly, leading to the behavior message displaying when I try to submit the form without filling the text input. Iβve checked the documentation and ensured that Iβm using the `validate` option properly. I also tried debugging with `console.log` to track the state of `watchCheckbox`, and it seems to update correctly as expected. Has anyone faced a similar scenario, and how can I fix the conditional validation for my form fields? Any insights would be greatly appreciated! Any help would be greatly appreciated! My team is using Javascript for this desktop app. I'd be grateful for any help.