Custom Error Messages
What you'll learn: How to replace Zod's generic validation errors with clear, user-friendly messages that match your application's tone and context.
The Problem with Default Errors
Zod's built-in error messages are functional but often too technical for end users. "String must contain at least 8 character(s)" works, but "Password must be at least 8 characters long" feels more natural and specific to your form's context.
Customizing Messages in Schema Definitions
You can override default messages by passing a message option to most Zod validation methods:
import { z } from 'zod';
const signupSchema = z.object({
email: z.string()
.min(1, { message: "Email is required" })
.email({ message: "Please enter a valid email address" }),
password: z.string()
.min(8, { message: "Password must be at least 8 characters long" })
.regex(/[A-Z]/, { message: "Password must contain at least one uppercase letter" }),
age: z.number({
required_error: "Age is required",
invalid_type_error: "Age must be a number"
})
.min(18, { message: "You must be 18 or older to sign up" })
});
Think Like Your Users
Custom messages let you speak in your users' language. Instead of validation jargon, explain what went wrong and how to fix it. "Username already taken" beats "Expected unique constraint violation" every time.
Context-Specific Messages
The same validation rule can have different messages depending on where it's used. A minimum length requirement might say "Name must be at least 2 characters" in one field and "Bio must be at least 2 characters" in another—same rule, different context.
Key Takeaway: Custom error messages transform technical validation feedback into helpful, context-aware guidance that improves the user experience without changing the underlying validation logic.