1import{ z }from'zod';23exportconstFormSchema= z.object({4id: z.string(),5customerId: z.string({6invalid_type_error:'Please select a customer.',7}),8amount: z.coerce.number().gt(0,{message:'Please enter an amount greater than $0.'}),9status: z.enum(['pending','paid'],{10invalid_type_error:'Please select an invoice status.',11}),12date: z.string(),13});
According to the official website, Zod is a TypeScript-first schema validation library with static type inference. It helps ensure your data matches the expected shape and types at runtime, while providing excellent TypeScript integration.
The goal is to eliminate duplication type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. This means you don't need to maintain separate type definitions and runtime validations.
Key Features:
Zero dependencies
Works in Node.js and all modern browsers
Tiny: 8kb minified + zipped
Immutable: methods (e.g. .optional()) return a new instance
Concise, chainable interface
Functional approach: parse, don't validate
Works with plain JavaScript too! You don't need to use TypeScript
Rich error messages and customizable error handling
Zod offers two methods for custom validation: refine and superRefine:
1// Basic refinement2constPasswordSchema= z
3.string()4.min(8)5.refine((password)=>/[A-Z]/.test(password),{6 message:'Password must contain at least one uppercase letter',7});89// Complex refinement with custom error handling10constFormSchema= z
11.object({12 password: z.string(),13 confirm: z.string(),14})15.superRefine((data, ctx)=>{16if(data.password!== data.confirm){17 ctx.addIssue({18 code: z.ZodIssueCode.custom,19 message:"Passwords don't match",20 path:['confirm'],// Path of the error21});22}23});
1constUserSchema= z.object({2 name: z.string(),3 email: z.string().email().optional(),// Field can be undefined4 phone: z.string().nullable(),// Field can be null5 age: z.number().optional().nullable(),// Field can be undefined or null6});
1constFormSchema= z.object({2 username: z
3.string({4 required_error:'Username is required',5 invalid_type_error:'Username must be a string',6})7.min(3,'Username must be at least 3 characters'),8});
Zod has become a handy tool for developers dealing with form validation, especially when combined with TypeScript. Using Zod's schema declaration and validation features, developers can ensure that the data entered into forms aligns with the specified structure and adheres to predefined validation rules.