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"])
})
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({...
Jump to solution
2 Replies
Lukem121
Lukem12116mo ago
You can use the errorMap.
Solution
Lukem121
Lukem12116mo ago
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>
);
}
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>
);
}
Want results from more Discord servers?
Add your server