react-hook-form / resolvers

📋 Validation resolvers: Yup, Zod, Superstruct, Joi, Vest, Class Validator, io-ts, Nope, computed-types, typanion, Ajv, TypeBox, ArkType, Valibot, effect-ts and VineJS
https://react-hook-form.com/
MIT License
1.72k stars 157 forks source link

Zod array length validation issues with `useFieldArray` #566

Closed vimtor closed 1 year ago

vimtor commented 1 year ago

Describe the bug

Zod array length validation does not trigger when using the append method from useFieldArray.

To Reproduce

  1. Use zod and @hookform/resolvers for validation.
  2. Create a field using useFieldArray.
  3. Add the zod schema for this field and set a minimum length for the array length AND a validation for the objects in the array.
  4. Submit the empty form to trigger the errors in the form since this field is empty. You see the proper validation error.
  5. Add a new field to the array
  6. The error still persists

Codesandbox link (Required)

https://codesandbox.io/s/react-hook-form-array-length-error-zod-b92w1t

Expected behavior A clear and concise description of what you expected to happen.

I should be able to validate the array length and its contents using

Screenshots

https://github.com/react-hook-form/react-hook-form/assets/36263538/949d8419-bc07-42a8-8b81-4973dbe9ea0e

Desktop (please complete the following information):

Kirdock commented 1 year ago

Also came to this error. The missing update is not the only thing that is wrong here. The field array errors should be put into a "root" object. With the current implementation of zodResolver, it always sets message and type for the field array and if this happens, all the other errors of its items are gone (but seems to be related to refine/superRefine for fieldArrays).

jorisre commented 1 year ago

You need to manually invoke the trigger method when adding to the field array. Validation doesn't occur automatically when a new field is registered.

https://codesandbox.io/s/react-hook-form-array-length-error-zod-forked-zjx7g7?file=/src/App.tsx

vimtor commented 1 year ago

Hi @jorisre!

I'm not trying to be mean, and I am super grateful that you and others developed react-hook-form. It's such a great library.

However, I think that the fact that the trigger is not invoked automatically when adding to a field array is in fact the issue. It seems to me that invoking the trigger manually is a workaround.

Thank you.