CodexBloom - Programming Q&A Platform

React Hook Form: Issues with Conditional Field Validation Based on Previous Inputs

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

I can't seem to get I'm stuck trying to I'm sure I'm missing something obvious here, but This might be a silly question, but I'm using React Hook Form (v7.0) to build a multi-step form where certain fields should be conditionally validated based on previous inputs..... Specifically, if the user selects a specific option in the first step, additional fields in the second step should become required. I've set up my form as follows: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; const MyForm = () => { const { control, handleSubmit, watch, setValue, register } = useForm(); const step1Choice = watch('step1Choice'); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="step1Choice" control={control} defaultValue="" render={({ field }) => ( <select {...field}> <option value="">Select an option</option> <option value="valid">Valid Option</option> <option value="invalid">Invalid Option</option> </select> )} /> <div> <label>Field A</label> <input {...register('fieldA', { required: step1Choice === 'valid' })} /> </div> <div> <label>Field B</label> <input {...register('fieldB', { required: step1Choice === 'valid' })} /> </div> <button type="submit">Submit</button> </form> ); }; ``` However, I'm running into issues where even when I select 'valid' in the first step, the validation for 'fieldA' and 'fieldB' isn't triggered properly. When I submit the form, I get the following error message: `"You must fill out all required fields."` I've tried using `setValue` to manually set the validation rules based on the choice made, but that doesn't seem to work as expected either. I also ensured that I am using the latest version of the library, but it feels like there's a disconnect between the conditional validation and the form state. What am I missing here? Are there any specific best practices for handling conditional validations in React Hook Form that I should follow? Is there a better approach? For context: I'm using Javascript on Ubuntu. Is there a better approach? How would you solve this? The stack includes Javascript and several other technologies. What's the best practice here? Any advice would be much appreciated. This is happening in both development and production on Windows 10. How would you solve this?