colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.92k stars 1.18k forks source link

z.union() ignores custom error message #3675

Open iwannatto opened 3 months ago

iwannatto commented 3 months ago
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 commented 2 months ago

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,
    });
  }
});