CodexBloom - Programming Q&A Platform

React Hook Form: Conditional Field Validation Not Triggering on Dynamic Fields

👀 Views: 152 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
react react-hook-form validation javascript

I've been banging my head against this for hours. I've been struggling with this for a few days now and could really use some help. I'm using React Hook Form (version 7.0) to manage a dynamic form, where fields are rendered based on user selection. However, I'm facing an issue with conditional validation not triggering as expected. I have a scenario where if the user selects a certain option, a specific field becomes required. I have set up the validation, but it seems that the validation is not enforced when the field is rendered dynamically. Here's a simplified version of my code: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; const MyForm = () => { const { control, handleSubmit, watch, setValue } = useForm(); const selectedOption = watch('option'); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="option" control={control} defaultValue="" render={({ field }) => ( <select {...field}> <option value="">Select an option</option> <option value="required">Requires Input</option> <option value="optional">Does Not Require Input</option> </select> )} /> {selectedOption === 'required' && ( <Controller name="requiredField" control={control} rules={{ required: 'This field is required' }} render={({ field, fieldState }) => ( <div> <input {...field} /> {fieldState.error && <p>{fieldState.error.message}</p>} </div> )} /> )} <button type="submit">Submit</button> </form> ); }; export default MyForm; ``` When I select the option that should trigger the required field, it does render correctly; however, upon submitting the form without filling it out, I do not see the validation error message. I'm also trying to call `setValue` manually to see if that changes anything, but it doesn't seem to help. I have checked the `react-hook-form` documentation and tried adjusting the rules, but nothing seems to fix the issue. Has anyone encountered this before, or can anyone suggest what I might be missing in the implementation? Has anyone else encountered this? My development environment is macOS. This is my first time working with Javascript 3.11. Thanks, I really appreciate it!