Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

z.union() ignores custom error message #3675

Open
iwannatto opened this issue Jul 25, 2024 · 1 comment · May be fixed by #3728
Open

z.union() ignores custom error message #3675

iwannatto opened this issue Jul 25, 2024 · 1 comment · May be fixed by #3728

Comments

@iwannatto
Copy link

import { z } from 'zod';

const schema = z.union([z.boolean(), z.number()], { message: 'custom error message' });

const result = schema.safeParse('hello');

if (!result.success) {
    console.log(result.error.errors);
}

In this code, I expect that result.error.errors emit my custom error message. But I got

[
  {
    code: 'invalid_union',
    unionErrors: [ [ZodError], [ZodError] ],
    path: [],
    message: 'Invalid input' // <- this should be 'custom error message'
  }
]

Is this specification or bug?

@mohamedtsx
Copy link

I’ve encountered the same issue with z.union() ignoring custom error messages. As a workaround, I’ve used a combination of optional and superRefine to ensure that my custom error message is respected. Here’s how I approached it:

import { z } from 'zod';

const schema = z.union([
  kuwaitAddress,
  baseAddress,
  z.coerce.number({
    required_error: path.addressNumber,
    message: path.addressNumber,
    invalid_type_error: path.addressNumber,
  }),
])
.optional()
.superRefine((val, ctx) => {
  if (val === undefined) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: path.address,
    });
  }
});

@sunnylost sunnylost linked a pull request Aug 28, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants