React Hook Form: How to conditionally display validation errors for dynamic fields?
I'm not sure how to approach I'm experimenting with I need help solving I'm getting frustrated with After trying multiple solutions online, I still can't figure this out..... I've searched everywhere and can't find a clear answer. I'm using React Hook Form v7 to manage a dynamic form with fields that are conditionally rendered based on user selections. The issue arises when I try to validate these fields and display error messages accordingly. For instance, I have a section that only appears if a user selects 'Yes' from a dropdown, which has a required text field. However, when I submit the form without filling this text field, the validation error does not show up as expected. 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 watchYes = watch('isYes'); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label> Do you want to enter additional info? <select {...register('isYes')}> <option value="no">No</option> <option value="yes">Yes</option> </select> </label> {watchYes === 'yes' && ( <div> <label> Additional Info: <input type="text" {...register('additionalInfo', { required: watchYes === 'yes' })} /> </label> {errors.additionalInfo && <span>This field is required</span>} </div> )} <input type="submit" /> </form> ); }; export default MyForm; ``` I've confirmed that the `required` validation rule is applied when the field is visible, but the error message doesn't trigger on form submission. I've tried different strategies like setting the validation conditionally or manually triggering validation in `onSubmit`, but nothing seems to work. Am I missing something in how dynamic fields are validated with React Hook Form? Any guidance on best practices for handling such cases would be greatly appreciated! What's the best practice here? Any help would be greatly appreciated! I recently upgraded to Javascript LTS. Any advice would be much appreciated. This is my first time working with Javascript 3.10. Is there a simpler solution I'm overlooking? Is there a simpler solution I'm overlooking? I'm working with Javascript in a Docker container on Windows 11. Am I approaching this the right way?