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.77k stars 161 forks source link

The schemaOptions errorMap is not working in certain scenarios - zod #585

Closed adamsujeta closed 1 year ago

adamsujeta commented 1 year ago

The errorMap function is not always replacing the message in the formState.errors object

Codesandbox link (Required)

The link to the old version of the resolver example (old packages): https://codesandbox.io/s/react-hook-form-zod-resolver-example-forked-fcz3g6

The link to the new version of the resolver example (updated packages): https://codesandbox.io/s/react-hook-form-zod-resolver-example-forked-updated-2zw4x9

To Reproduce Steps to reproduce the behavior:

  1. Go to codesandbox
  2. Click on buttons: "test undefined" , "test to small" , and "test to big"
  3. See that the message of the error is not showing what the errorMap function is always returning ("correct msg")
  4. See that(only as info) old packages and updated packages codesandbox'es have different behavior: the old version is showing the incorrect error msg also when clicking on the test undefined button

Expected behavior I would expect that every error message would equal to what was specified in the errorMap function.

const incorrectMsg = "incorrect error msg";
const correctMsg = "correct msg";

const schema = z.object({
    value: z
        .string({
            required_error: incorrectMsg,
            invalid_type_error: incorrectMsg,
        })
        .nonempty(incorrectMsg)
        // .nonempty({message: incorrectMsg})
        .max(5),
});

function errorMap(issue, ctx) {
  console.log("errorMap", { issue, ctx });
  return { message: correctMsg };
}

The result of the tests (clicking on the buttons) that i'm currently getting:

value: { message: 'correct msg', type: 'invalid_type' }
value: { message: 'incorrect error msg', type: 'too_small' }
value: { message: 'correct msg', type: 'too_big' }

What i would expect after clicking on the buttons:

value: { message: 'correct msg', type: 'invalid_type' }
value: { message: 'correct msg', type: 'too_small' }
value: { message: 'correct msg', type: 'too_big' }
adamsujeta commented 1 year ago

Sorry this is a zod problem not react hook form resolvers. I found an issue in zod repo.