I have an array of fields with an input field for which I have set some validation rules such asrequired
andminLength
.
I want the new field to be validated immediately when it is appended. However, this doesn't happen and even if I append empty fields, the error for these input fields remains undefined:
function App() { const useFormMethods = useForm({ defaultValues: { test: [{ firstName: "Bill", lastName: "Luo" }] }, mode: "onChange" }); const { fields, append, remove } = useFieldArray({ control: useFormMethods.control, name: "test", rules: { minLength: 4 } }); const onSubmit = (data) => console.log("data", data); return (); }
This is controlled input that needs to be validated:
export const FormControlledInput = ({ name }) => { const { control, formState: { errors } } = useFormContext(); const { field, fieldState } = useController({ name, control, rules: { required: true } }); console.log(`fieldState error: `, fieldState.error); console.log(`formState errors: `, errors); return ; };
You can see working code and box examples here. What do I need to do to make it validate every time I change it?
The
append
method used to add fields to the array is asynchronous, and thetrigger
method that performs validation is also asynchronous, so there is a race condition that causes the field to be registered before it is registered with the array. Trigger verification form. You can justawait
the function result before triggering revalidation when adding an array field.I forked your CSBhere. I also added a
useEffect
hook that will trigger validation when the component is installed.