Default Values
Zod can provide default values for missing fields.
For example, in the schema below, the published field defaults to false if not provided, and tags defaults to an empty array:
const postSchema = z.object({
title: z.string().min(1, "Title is required"),
content: z.string().min(1, "Content is required"),
published: z.boolean().default(false),
tags: z.array(z.string()).default([]),
});
Number Validation
For numeric fields like ratings or ages:
const restaurantSchema = z.object({
name: z.string().min(2, "Name must be at least 2 characters"),
rating: z
.number()
.min(1, "Rating must be at least 1")
.max(5, "Rating must not exceed 5"),
});
Transform Data
Zod can transform data while validating. This example trims whitespace from email addresses:
const userSchema = z.object({
username: z.string().min(2),
email: z
.email("Must be a valid email")
.transform((val) => val.trim().toLowerCase()),
});
After validation, emails are automatically cleaned up, so " John@Example.Com " becomes "john@example.com".