Last Updated: 3/12/2026
Custom Errors
Customize error messages for better user experience.
Inline Messages
Pass error messages directly to validators:
import * as z from "zod";
const Username = z.string()
.min(3, "Username must be at least 3 characters")
.max(20, "Username cannot exceed 20 characters")
.regex(/^[a-zA-Z0-9_]+$/, "Only letters, numbers, and underscores allowed");Message Objects
Provide detailed error configuration:
const Age = z.number().min(18, {
message: "You must be at least 18 years old",
});Custom Error Maps
Define global error message formatting:
import { z } from "zod";
z.setErrorMap((issue, ctx) => {
if (issue.code === "invalid_type") {
return { message: `Expected ${issue.expected}, got ${issue.received}` };
}
return { message: ctx.defaultError };
});Per-Schema Error Maps
Override errors for specific schemas:
const schema = z.string({
errorMap: (issue, ctx) => {
if (issue.code === "too_small") {
return { message: "String is too short!" };
}
return { message: ctx.defaultError };
},
});What’s Next
- Error Handling — Handle and format validation errors
- Refinements — Add custom validation logic