I have some questions regarding react hook form and the way it validates the array fields.
I was trying to register the array field with useEffect when the component mounts but then I noticed there is a useFieldArray hook which is not mounting anything until you append a field.
So I have this:
const { fields, append, remove } = useFieldArray<FieldValues>({
name: `logic.${index}.questions` as 'logic.0.questions',
})
And I am able to see that field until the select element hits the onChange event.
<Select onChange={e => append({ id: e.target.value }) }>...</Select>
And depending on what I append, the fields value from useFieldArray starts to grow its length so I am able to render new things based on that, like:
<Box>
{ fields.map((field) => <Text key={field.id}>{ field.id }</Text> )}
</Box>
So for example here https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-x7btr?file=/src/index.js
How would you validate on submit, that the array has a positive length (> 0) and show an error message.
I noticed you can do that easily when the fields are only objects, but what can I do to validate for example if the code I posted here using useFieldArray, if the fields length is more than 0 then submit the form, otherwise show an error (?)
There's a recent new feature in react-hook-form v7.34.0 that provides this kind of validation out of the box...
You set it up when you define the field array
In your case, you want the rule required: true
useFieldArray({
name: 'test',
rules: {
required: true,
}
})
And then you check for/use the error as such
errors?.test?.root?.message
Note, there is another variant that allows you to provide a custom error message if the required check fails...
e.g.
rules: {
required: {
value: true,
message: "At least one is required",
}
}
See here for further details...
https://react-hook-form.com/api/usefieldarray/
https://github.com/react-hook-form/react-hook-form/issues/6879
https://github.com/react-hook-form/react-hook-form/pull/8562
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With