React Hook Form: how to to trigger validation on dynamic fields after adding/removing them
I've looked through the documentation and I'm still confused about This might be a silly question, but After trying multiple solutions online, I still can't figure this out. I'm building a dynamic form using React Hook Form (version 7.0) and I'm working with issues with validation of fields that I dynamically add and remove. I have a scenario where users can add multiple phone numbers, and each phone number field should be validated to ensure it matches a specific regex pattern. I've set up my form with `useForm` and I'm using `Controller` to handle the dynamic inputs. After adding a new phone number field, the validation message does not appear until the form is submitted. I have already tried calling `trigger` on the specific field after pushing a new value to the array, but it seems to be ineffective. Hereโs a simplified version of my code: ```javascript import React, { useState } from 'react'; import { useForm, Controller } from 'react-hook-form'; const PhoneForm = () => { const { control, handleSubmit, trigger, setValue, formState: { errors } } = useForm(); const [phoneNumbers, setPhoneNumbers] = useState(['']); const addPhoneNumber = () => { setPhoneNumbers([...phoneNumbers, '']); trigger(`phoneNumbers.${phoneNumbers.length}`); // Trying to trigger validation }; const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {phoneNumbers.map((_, index) => ( <Controller key={index} name={`phoneNumbers.${index}`} control={control} rules={{ required: true, pattern: { value: /^\d{10}$/, message: 'Phone number must be 10 digits' } }} render={({ field }) => <input {...field} />} /> ))} {errors.phoneNumbers && <p>{errors.phoneNumbers.message}</p>} <button type="button" onClick={addPhoneNumber}>Add Phone Number</button> <button type="submit">Submit</button> </form> ); }; export default PhoneForm; ``` Currently, when I add a new phone number field, the validation doesnโt trigger until I submit the form. I want the validation to check immediately as soon as the user finishes typing in the field. I've also checked if the `trigger` function's parameter is correctly targeting the new input, but validation messages still donโt show until submission. Any insights on how to handle validation for dynamically added fields more effectively? Thanks in advance! I'd really appreciate any guidance on this. I've been using Javascript for about a year now.