robertLichtnow / zod-formik-adapter

An adapter for zod object validation to Formik validation schema
https://www.npmjs.com/package/zod-formik-adapter
MIT License
160 stars 15 forks source link

Does not support errors coming from zodSchema.refine() #15

Open shobhanbiswas11 opened 2 years ago

shobhanbiswas11 commented 2 years ago

Describe the bug Does not parse properly if the error is coming from refine or superRefine

To Reproduce

const formSchema = z
  .object({
    username: z.string().email(),
    firstName: z.string(),
    middlerName: z.string().optional(),
    lastName: z.string(),
    password: z.string(),
    confirmPassword: z.string(),
    status: z.enum(['active', 'inactive']),
  })
  .refine((data) => data.password !== data.confirmPassword, {
    message: "Passwords don't match",
    path: ['confirmPassword'], // path of error
  });

if the values are these

{
      username: 'name',
      firstName: 'fname',
      lastName: 'lname',
      middlerName: 'mname',
      password: 'ss',
      confirmPassword: 'ssad',
      status: 'active',
}

It does not add any error for confirmPassword field with message "Passwords don't match"

Node version: v16.15.0

Zod, Formik and zod-formik-adapter versions:

iest commented 2 years ago

I ran into this issue — it actually does work; however the refine & superRefine methods don't get called if there are validation errors coming from inside that object — so only if there are no other errors will the errors from refine/superRefine actually surface.

This is an issue with how Zod works, rather than this library.

Edit: Actually you're right; the errors don't surface at all with this package. I copy-pasted the main index.ts into my codebase and got it working like I detailed above. Super weird

robertLichtnow commented 1 year ago

@iest can you add which versions of Zod and Formik you were using when testing?

iest commented 1 year ago

@robertLichtnow not 100% sure as it's been a few months, but my yarn.lock says formik: ^2.2.9 and zod: ^3.19.1

alexkuc commented 1 year ago

I observed the same behaviour and noticed the following… In my case, I have custom input control driven by Formik's useField() hook. It's a custom combobox with ability to specify custom value. Here are my observations where .refine is defined for all conditions:

Edit: added 4th bullet point

alexkuc commented 1 year ago

Another observation I noticed today. If you define .refine() on schema itself, not individual field, it is also ignored.

veksen commented 1 year ago

Is there a workaround people are using for this? I'd specifically like to do password confirmation

sendyputra commented 1 year ago

try assign validate to formik validate={toFormikValidate(Schema)} and its work

Screen Shot 2023-09-12 at 16 50 02 Screen Shot 2023-09-12 at 16 54 05 Screen Shot 2023-09-12 at 16 51 51