Quick Start
This quick start guide will walk you through the standard workflow of validating data with Zod and catching/formatting errors using zod-validation-error.
Step 1: Configure the Global Error Map (Optional but Recommended)
Zod allows you to override its default, internal error messages using an "Error Map". By passing zod-validation-error's createErrorMap() to Zod globally, you ensure that even if you inspect a raw ZodIssue directly, the message will be formatted beautifully.
import { z as zod } from 'zod';
import { fromError, createErrorMap } from 'zod-validation-error';
// 1. (Optional) Configure Zod to use zod-validation-error's error map.
// This provides inherently better user-friendly messages directly from Zod.
zod.config({
customError: createErrorMap(),
});
// 2. Create a standard Zod schema
const zodSchema = zod.object({
id: zod.int().positive(),
email: zod.email(),
});
// 3. Parse data safely
try {
zodSchema.parse({
id: 1,
email: 'coyote@acme', // This will fail validation (invalid email)
});
} catch (err) {
// 4. Convert the unknown error into a user-friendly ValidationError
const validationError = fromError(err);
// The error is now readable by the user:
console.log(validationError.toString());
// Output: Validation error: Invalid email address at "email"
// You can still access the original Zod issues if needed:
console.log(validationError.details);
}
Next Steps
- Explore the Usage Guide to see how to implement this in an Express API or with React Hook Form.
- Learn how to customize prefixes and separators in the createMessageBuilder API docs.
- Understand how to safely identify error types using Type Guards.