Data Validation
on this page
Basic usage
Lets start simple, and see how data validation works in Zod. Consider a number representing the month number in a year. We know that its value can be between 1-12, and it has to be an integer. Lets see how we can express this requirement in Zod.
import { z } from "zod";
const MonthNumberSchema = z.number().int().min(1).max(12);
const wrongMonth = 13
MonthNumberSchema.parse(wrongmonth)
/*Throws error*/
In the above example, we have initialized a number
schema, and applied the int, min, and max constraints on it. Then we called the parse
method on the schema. If the value does not fall within the constraints, it will throw an error.
Basic Primitive Schema Types
Zod provides the following primitive schema types:
- string
- number
- bigint
- boolean
- date
- symbol
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();
// empty types
z.undefined();
z.null();
z.void(); // accepts undefined
// catch-all types
// allows any value
z.any();
z.unknown();
// never type
// allows no values
z.never();
Each of these schemas have their own specific methods/constraints. Please refer to the documentation for their specific usage.
Object Schema
To validate JavaScript objects, we can use the object schema in Zod. It is a schema composed of other Zod Schemas, with any level of nesting. Lets see an example.
const PersonSchema = z.object({
name: z.string().min(1),
age: z.number().int().min(0),
});
PersonSchema.parse({
name : 'john',
age : -1
});
/*Will fail as the age is less than 0*/
We can use the above schema to validate an object representing a personβs name, and age.
Array Schema
Apart from scalar values, and objects, we can also validate arrays in Zod.
const namesSchema = z.array(z.string().min(1));
const names = ['john', 'jane', 'bob', ''];
namesSchema.parse(names);
/*Will fail as the last name is empty*/
We can combine all the array, object, and primitive schemas to represent any type of data.
Example Scenario
Assume the following scenario. You are fetching the data for a blog post from your database. It has the following attributes with constraints mentioned:
- postId : number
- title : non empty string
- body : non empty string
- authorName : non empty string
- tags : an array of non empty strings
Lets construct a Zod object schema to validate a blog post.
const postSchema = z.object({
postId : z.number(),
title : z.string().min(1),
body : z.string().min(1),
authorName : z.string().min(1),
tags : z.array(z.string().min(1))
});
We can further extend this to an array of blog posts too.
const postArraySchema = z.array(postSchema);