javascript - How can I validate array field in React Hook Form with the useFieldArray hook? - Stack Overflow

I have some questions regarding react hook form and the way it validates the array fields.I was trying

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 ponent 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 =/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 (?)

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

Share Improve this question asked Jul 29, 2021 at 7:34 ReactingReacting 6,1438 gold badges42 silver badges95 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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./api/usefieldarray/

https://github./react-hook-form/react-hook-form/issues/6879

https://github./react-hook-form/react-hook-form/pull/8562

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744479311a4576179.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信