CodexBloom - Programming Q&A Platform

React Hook Form: Conditional Validation Not Triggering on Checkbox Change

๐Ÿ‘€ Views: 59 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-14
react react-hook-form validation JavaScript

I'm stuck trying to I've been struggling with this for a few days now and could really use some help. I've tried everything I can think of but I'm stuck on something that should probably be simple..... I'm relatively new to this, so bear with me. I'm using React Hook Form (version 7.2.0) in my project, and I've set up a form that includes a checkbox which is supposed to conditionally validate a text input based on whether the checkbox is checked or not. However, the validation doesn't seem to trigger correctly when I check or uncheck the checkbox. 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 isChecked = watch('terms'); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <div> <label> <input type="checkbox" {...register('terms')} /> Accept Terms </label> </div> <div> <input type="text" {...register('username', { required: isChecked ? 'Username is required when terms are accepted' : false })} /> {errors.username && <p>{errors.username.message}</p>} </div> <button type="submit">Submit</button> </form> ); }; export default MyForm; ``` In this setup, when the checkbox is checked, the username field should be required, and if itโ€™s not filled out, it should display an behavior message. The question is that even after checking the checkbox, the validation does not seem to activate. I've tried using the `watch` function to dynamically check the state of the checkbox, but the behavior message doesnโ€™t show up as expected. I've also ensured that the `username` field is registered after the checkbox state change. Is there something I'm missing in the configuration or use of the React Hook Form that could cause this conditional validation to unexpected result? Iโ€™ve looked through the documentation but need to seem to find a solution. Any help would be appreciated! What am I doing wrong? The stack includes Javascript and several other technologies. Thanks for any help you can provide! What's the best practice here? The project is a application built with Javascript. Is there a simpler solution I'm overlooking? This is my first time working with Javascript latest. I'm open to any suggestions.