Zod Basics#
Primitive Types#
import { z } from 'zod';
z.string(); // string
z.number(); // number
z.boolean(); // boolean
z.null(); // null
z.undefined(); // undefined
z.any(); // any
z.unknown(); // unknown
Validation Methods#
String Validations#
z.string().min(5); // min length
z.string().max(20); // max length
z.string().email(); // email format
z.string().url(); // URL format
z.string().uuid(); // UUID format
z.string().regex(/^\d+$/); // custom regex
z.string().startsWith("https://"); // prefix
z.string().endsWith(".com"); // suffix
Number Validations#
z.number().min(0); // minimum value
z.number().max(100); // maximum value
z.number().int(); // integers only
z.number().positive(); // > 0
z.number().negative(); // < 0
z.number().nonnegative(); // >= 0
z.number().multipleOf(5); // divisible by 5
Optional & Nullable#
z.string().optional(); // string | undefined
z.string().nullable(); // string | null
z.string().nullish(); // string | null | undefined
z.string().default("hello"); // default value if undefined
Arrays#
z.array(z.string()); // string[]
z.string().array(); // same as above
z.array(z.number()).min(1); // at least 1 item
z.array(z.number()).max(5); // at most 5 items
z.array(z.number()).length(3); // exactly 3 items
Safe Parse#
const result = schema.safeParse(data);
if (result.success) {
console.log(result.data);
} else {
console.log(result.error.issues);
}
Use safeParse in production
safeParse returns a result object instead of throwing, making it safer for production use.