Setting Custom Error Messages on Zod Unions

Hello, I'd like to set a custom error message when a union of literals does not pass parsing in zod. With other constraints, such as .min() or .max() you can set a error message like this:
email: z
.string()
.email({ message: "Email must be a valid email (eg: someone@example.com).",})
.max(255, { message: "Email must be less than 255 characters." }),
email: z
.string()
.email({ message: "Email must be a valid email (eg: someone@example.com).",})
.max(255, { message: "Email must be less than 255 characters." }),
But I am not sure how to do so on this union:
gender: z.union([
z.literal("MALE"),
z.literal("FEMALE"),
z.literal("NON-BINARY"),
z.literal("OTHER"),
z.literal("PREFERNOTSAY"),
]),
gender: z.union([
z.literal("MALE"),
z.literal("FEMALE"),
z.literal("NON-BINARY"),
z.literal("OTHER"),
z.literal("PREFERNOTSAY"),
]),
Could anyone help me out? Thanks!
1 Reply
Alan Ibarra-2310
Alan Ibarra-231013mo ago
I'm not really sure how to do it. I usually just safeParse the union and if it was unsuccessful, I just write my own error message. But, if this was meant to be used in multiple places then coupling the error message with the union would be a better solution.