Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
2 replies
Liam

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." }),


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"),
]),


Could anyone help me out? Thanks!
Was this page helpful?