Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
4 replies
clemwo

How to customize zod union error message?

I have a zod schema like so:
const schema = z.object({
  customer: z.union([z.string().uuid(), z.literal("allCustomers"])
})


How can I customize the error message when customer is undefined?
Solution
import React from "react";
import { z } from "zod";

export default function Page() {
  const schema = z.object({
    customer: z.union(
      [
        z.string().uuid({
          message: "Customer must be a valid UUID",
        }),
        z.literal("allCustomers", {
          errorMap: (error) => {
            // console.log("Zod Literal Error", error);

            if (error.code === "invalid_literal") {
              return {
                message: "Yo this is not 'allCustomers' ???",
              };
            }

            return {
              message: error.message ?? "There was an error",
            };
          },
        }),
      ],
      {
        errorMap: (error) => {
          // console.log("Zod Union Error", error);

          if (error.code === "invalid_union") {
            return {
              message: "Yo this is not a valid union ???",
            };
          }

          return {
            message: error.message ?? "There was an error",
          };
        },
      },
    ),
  });

  return (
    <div>
      <button
        onClick={() => {
          const result = schema.safeParse({ customer: undefined });
          if (result.success) {
            console.log(result.data);
          } else {
            console.log(result.error.errors.map((error) => error.message));
          }
        }}
      >
        Click me!
      </button>
    </div>
  );
}
Was this page helpful?