What is Zod?
Zod is a schema-based data validation library for TypeScript. With its TypeScript-first approach, it automatically infers TypeScript types from the schemas you define.
It combines runtime validation with static type inference to provide type safety both at development and runtime.
Basic Schemas
With Zod, you can define schemas for basic types like string, number, boolean, and object. z.string(), z.number(), and z.object() are the most commonly used schemas.
Each schema can be customized with chainable methods like .min(), .max(), and .email().
Advanced Validation
Zod allows you to add custom validation logic with refine and superRefine. It also offers advanced features like discriminatedUnion and z.infer.
Email validation with z.string().email() Array validation with z.array().min(1) Discriminated unions with z.discriminatedUnion Custom rules with z.refine
API and Form Integration
Zod works seamlessly with tRPC and React Hook Form. It is ideal for input validation at API endpoints or form validation.
TypeScript Integration
One of Zod's strongest features is its ability to infer TypeScript types from schemas using z.infer. This allows you to define both validation and type definitions from a single source.