CodexBloom - Programming Q&A Platform

React Hook Form: Validation Not Triggering on Conditional Field Visibility

πŸ‘€ Views: 69 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
react react-hook-form validation javascript

I'm using React Hook Form (v7.0.0) to manage form state, and I'm working with an scenario with validation not triggering for a conditional field that appears based on a checkbox selection. I have a checkbox that, when checked, should display an additional input field that requires validation. However, when I check the box and fill out the input field, the validation errors are not showing up as expected. Here's a snippet of my code: ```jsx import React from 'react'; import { useForm } from 'react-hook-form'; const MyForm = () => { const { register, handleSubmit, watch, formState: { errors } } = useForm(); const isExtraFieldVisible = watch('showExtraField'); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label> <input type="checkbox" {...register('showExtraField')} /> Show Extra Field </label> {isExtraFieldVisible && ( <div> <input type="text" {...register('extraField', { required: isExtraFieldVisible })} placeholder="This field is required" /> {errors.extraField && <p>{errors.extraField.message}</p>} </div> )} <button type="submit">Submit</button> </form> ); }; ``` I've tried logging the `errors` object, and it seems that the validation condition is not evaluated correctly when the checkbox is toggled. The input field shows up, but even if I leave it empty when the checkbox is checked, the behavior message doesn't appear. I've also ensured that the `required` validation only triggers when the field is visible by referencing `isExtraFieldVisible` in the `register` options, but it still doesn’t work as intended. Could this be a question with how React Hook Form manages conditional fields? Is there a better way to handle this scenario to ensure that validations are triggered appropriately when the field becomes visible?