CodexBloom - Programming Q&A Platform

Next.js Form with Dynamic Validation scenarios to Trigger on Field Change - Need Guidance

👀 Views: 16 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
Next.js react-hook-form validation forms JavaScript

This might be a silly question, but I'm stuck on something that should probably be simple... I'm working on a Next.js application where I have a form that includes dynamically added fields based on user selection. However, I'm working with an scenario where the validation does not trigger properly when I change the selection for the dynamic fields. The validation should check if a specific condition is met based on the selected option, but it seems to be bypassing the validation entirely. Here's a simplified version of my component: ```javascript import { useState } from 'react'; import { useForm } from 'react-hook-form'; const DynamicForm = () => { const { register, handleSubmit, watch, setValue, trigger } = useForm(); const [fields, setFields] = useState([]); const onSubmit = data => { console.log(data); }; const handleSelectChange = (e) => { const selectedValue = e.target.value; // Clear previous fields and set new ones based on selection setFields(selectedValue === 'option1' ? ['field1'] : ['field2']); // Trigger validation for new fields trigger(); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <select onChange={handleSelectChange}> <option value=''>Select an option</option> <option value='option1'>Option 1</option> <option value='option2'>Option 2</option> </select> {fields.map((field, index) => ( <div key={index}> <input {...register(field, { required: true })} /> {errors[field] && <span>This field is required</span>} </div> ))} <button type='submit'>Submit</button> </form> ); }; export default DynamicForm; ``` I've tried using the `trigger()` method after updating the fields to ensure that validation is executed, but it seems the errors aren't being displayed as expected. I'm using `react-hook-form` version 7.0.0. When I submit the form without filling the dynamic fields, I get no validation messages. Am I missing something in the implementation? How can I ensure that the validation runs correctly whenever the dynamic fields change? For context: I'm using Javascript on Ubuntu. For context: I'm using Javascript on Linux. For context: I'm using Javascript on Windows. Has anyone else encountered this?