CodexBloom - Programming Q&A Platform

React Hook Form - Conditional Field Validations Not Triggering as Expected

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-24
react react-hook-form validation JavaScript

I'm integrating two systems and After trying multiple solutions online, I still can't figure this out... I'm sure I'm missing something obvious here, but I'm using React Hook Form (v7.0.0) for handling my form, and I'm working with an scenario where conditional field validations aren't triggering correctly. I have a form with a checkbox that, when checked, should make an email input field required. However, even when the checkbox is checked, I'm not seeing the validation errors 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 watchCheckbox = watch('subscribe'); // watching the checkbox state const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label> <input type="checkbox" {...register('subscribe')} /> Subscribe to newsletter </label> <label> Email: <input type="email" {...register('email', { required: watchCheckbox })} /> </label> {errors.email && <p>{errors.email.message}</p>} <button type="submit">Submit</button> </form> ); }; export default MyForm; ``` In the above code, I'm trying to make the email field required only if the checkbox is checked. However, when I submit the form with the checkbox checked and leave the email field empty, I don't see the expected behavior message saying the email field is required. I've also tried using a `setValue` method to programmatically update the validation rules, but it doesn't seem to solve the scenario. Is there a better way to handle conditional validations with React Hook Form? What am I missing here that’s preventing the validation from triggering as expected? How would you solve this? Am I missing something obvious? Any advice would be much appreciated.