Zod
Table of Contents
1. Schemas
Define and export a zod schema like so:
export const personalInformationSchema = z.object({
name: z.string(),
email: z.email(),
phone: z.string(),
birthday: z.date()
});
2. Validations
2.1. Strings
z.string().max(5);
z.string().min(5);
z.string().length(5);
z.string().regex(/^[a-z]+$/);
z.string().startsWith("aaa");
z.string().endsWith("zzz");
z.string().includes("---");
z.string().uppercase();
z.string().lowercase();
z.email(); // zod v3: z.string().email()
z.uuid();
z.url();
z.emoji(); // validates a single emoji character
z.base64();
z.base64url();
z.nanoid();
z.cuid();
z.cuid2();
z.ulid();
z.ipv4();
z.ipv6();
z.cidrv4(); // ipv4 CIDR block
z.cidrv6(); // ipv6 CIDR block
z.iso.date(); // YYYY-MM-DD, zod v3: z.string().date()
z.iso.time();
z.iso.datetime();
z.iso.duration();
2.1.1. Example: ZIP Code
Use string().regex() for ZIP code validation:
z.string().regex(/^\d{5}(-\d{4})?$/);
2.2. Date
Validates a Date instance. For HTML input, use the string validation z.iso.date() instead.
z.date();
z.date().safeParse(new Date()); // success: true
z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false
2.3. Enums
Ensures input is within a collection of allowable inputs.
const fish = ["Salmon", "Tuna", "Trout"] as const; // as const needed for type inference
const FishEnum = z.enum(fish);
2.4. Numbers
z.number() allows any finite number.
z.number().gt(5);
z.number().gte(5); // alias .min(5)
z.number().lt(5);
z.number().lte(5); // alias .max(5)
z.number().positive();
z.number().nonnegative();
z.number().negative();
z.number().nonpositive();
z.number().multipleOf(5); // alias .step(5)
2.5. Refinements
Every zod schema has an array of refinements, which allow for performing custom validation that zod doesn't provide an API for. Refinements should return a falsy value to signal validation failure.
const myString = z.string().refine((val) => val.length > 8, {
error: "Too short!"
});
2.6. Instanceof
Use z.instanceof() to check if input is an instance of a class.
class Test {
name: string;
}
const TestSchema = z.instanceof(Test);
2.6.1. Example: File Input
We can ensure the input is a file and validate the size of the file using z.instanceof() and refine():
const schema = z.object({
image: z
.instanceof(File, { message: 'Please upload a file.'})
.refine((f) => f.size < 100_000, 'Max 100 kB upload size.')
});