Handling form validation with React Hook Form and conditional fields
I've encountered a strange issue with I'm integrating two systems and I'm converting an old project and I'm working on a form using React Hook Form v7, and I'm trying to implement conditional validation based on user selections... The scenario arises when I need to conditionally validate fields that are only displayed if a certain option is selected. For example, I have a dropdown where if the user selects 'Other', a text input should appear, and this text input needs to be required. 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 selectedOption = watch('category'); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <select {...register('category')}> <option value=''>Select a category</option> <option value='default'>Default</option> <option value='other'>Other</option> </select> {selectedOption === 'other' && ( <input type='text' {...register('otherCategory', { required: selectedOption === 'other' })} /> )} {errors.otherCategory && <span>This field is required</span>} <button type='submit'>Submit</button> </form> ); }; export default MyForm; ``` The question is that even if I select 'Other' and leave the input empty, the behavior message does not show up. I've also tried adding a conditional check in the `register` method, but that doesn't seem to work either. The other fields validate correctly, so I'm not sure where I went wrong. Additionally, I've checked the React Hook Form documentation, but I couldn't find a clear example that addresses dynamic field validation under these conditions. Am I missing something in the way I register the dynamic field, or is there a better approach to handling conditional validations in React Hook Form? I'm using Javascript stable in this project. I'm open to any suggestions. I'm working in a Windows 10 environment. I'm developing on Debian with Javascript.