Refinements and Transformations
You'll learn how to add custom validation rules and transform parsed data using Zod's refine and transform methods.
What Are Refinements?
Sometimes Zod's built-in validators aren't enough. Refinements let you add custom validation logic after the basic type checks pass. Think of them as extra gatekeepers that say "the data is the right type, but does it meet our specific business rules?"
Use .refine() to add a custom validation function:
import { z } from 'zod';
const passwordSchema = z.string()
.min(8)
.refine(
(val) => /[A-Z]/.test(val),
{ message: "Password must contain an uppercase letter" }
);
passwordSchema.parse("weakpass"); // ❌ Fails refinement
passwordSchema.parse("StrongPass123"); // ✅ Passes
The refinement function receives the value and returns true if valid, false otherwise.
What Are Transformations?
Transformations let you modify data after validation passes. Use .transform() to convert the parsed result into a different shape or type:
const dateSchema = z.string().transform((str) => new Date(str));
const result = dateSchema.parse("2024-01-15");
// result is now a Date object, not a string
const trimmedSchema = z.string().transform((s) => s.trim().toLowerCase());
trimmedSchema.parse(" Hello World "); // Returns "hello world"
Transformations are useful for normalizing input, converting types, or enriching data before your application uses it.
Chaining Both
You can combine refinements and transformations:
const emailSchema = z.string()
.refine((s) => s.includes('@'), "Must be an email")
.transform((s) => s.toLowerCase());
Key Takeaway: Use .refine() to add custom validation rules beyond basic types, and .transform() to reshape validated data into the exact format your application needs.