React hook form field array validation not working
P粉665679053
P粉665679053 2023-12-06 19:41:46
0
1
407

I have an array of fields with an input field for which I have set some validation rules such asrequiredandminLength.

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 (  

Field Array

Render Count: {renderCount}
    {fields.map((item, index) => { 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?

P粉665679053
P粉665679053

reply all (1)
P粉404539732

Theappendmethod used to add fields to the array is asynchronous, and thetriggermethod 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 justawaitthe function result before triggering revalidation when adding an array field.

I forked your CSBhere. I also added auseEffecthook that will trigger validation when the component is installed.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!