How to customize zod union error message?
I have a zod schema like so:
How can I customize the error message when customer is undefined?
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"])
})
Solution:Jump to solution
```import React from "react";
import { z } from "zod";
export default function Page() {
const schema = z.object({...
2 Replies
You can use the errorMap.
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>
);
}
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>
);
}