How can I validate array field in React Hook Form with the useFieldArray hook?

Viewed 2841

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 (?)

1 Answers

It might not be exactly what you're looking for but here's how I solved it. I have a similar setup as in the codesandbox you shared, just without nested fields and including a Remove button that will remove the last fieldArray element when clicked:

<button onClick={() => controlledFields.length > 1 ? remove(controlledFields.length - 1) : null}>
  Remove
</button>

This is quite important, because I'm using required:true validation within fieldArray.map(), forcing the user to remove empty input fields and filling at least the first one. In your provided example this would be

<Box>
  { 
    fields.map((field) => (
      <>
      <Text 
        key={field.id}
        {...register(`fields.${index}`, {required:true})}
       >
      { field.id }
      </Text> 
      { errors.fields?.[index] && 
          <p> { index === 0 ? "Must select at least one" : "Remove empty fields if unused" } </p>
      }
      </>
    ))
  }
</Box>
Related