Skip to main content

Lesson 3 of 8

Zod Schema Validation

Zod is a TypeScript-first schema validation library. Its key innovation: the schema IS the type definition - `z.infer<typeof schema>` gives you the TypeScript type for free, with no duplication. Used with react-hook-form, it provides end-to-end type safety from schema to form to submission.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Zod - Complete Schema Reference

Zod - Complete Schema Reference
import { z } from 'zod';

// ---- Primitive types ----
const nameSchema = z.string().min(1).max(100).trim();
const ageSchema = z.number().int().min(0).max(120);
const emailSchema = z.string().email();
const urlSchema = z.string().url();
const phoneSchema = z.string().regex(/^\+?[1-9]\d{1,14}$/, 'Invalid phone number');
const uuidSchema = z.string().uuid();

// ---- Object schemas ----
const userSchema = z.object({
  id: z.string().uuid().optional(),          // optional UUID
  name: z.string().min(2, 'Name required'),
  email: z.string().email('Invalid email'),
  age: z.number().positive().optional(),
  role: z.enum(['admin', 'user', 'guest']),
  metadata: z.record(z.string()),            // { [key: string]: string }
  tags: z.array(z.string()).max(10),
  createdAt: z.string().datetime(),          // ISO 8601
});

// TypeScript type inferred from schema
type User = z.infer<typeof userSchema>;
// Same as: interface User { id?: string; name: string; email: string; age?: number; ... }

// ---- Transformations ----
const trimmedEmail = z.string().email().transform(s => s.toLowerCase().trim());

// ---- Refinements - custom validation ----
const passwordSchema = z.string()
  .min(8, 'At least 8 characters')
  .regex(/[A-Z]/, 'One uppercase letter')
  .regex(/[a-z]/, 'One lowercase letter')
  .regex(/[0-9]/, 'One number')
  .regex(/[^A-Za-z0-9]/, 'One special character');

// Cross-field refinement
const signupSchema = z.object({
  password: passwordSchema,
  confirmPassword: z.string(),
}).refine(
  data => data.password === data.confirmPassword,
  { message: "Passwords don't match", path: ['confirmPassword'] }
);

// ---- Discriminated unions ----
const paymentSchema = z.discriminatedUnion('method', [
  z.object({ method: z.literal('card'), cardNumber: z.string().length(16), cvv: z.string().length(3) }),
  z.object({ method: z.literal('paypal'), paypalEmail: z.string().email() }),
  z.object({ method: z.literal('crypto'), walletAddress: z.string() }),
]);

// ---- Parsing ----
const result = userSchema.safeParse(unknownData);
if (result.success) {
  const user = result.data;   // TypeScript knows user is User type
} else {
  const errors = result.error.flatten();
  // errors.fieldErrors: { name?: string[], email?: string[] }
  // errors.formErrors: string[]
}

// ---- Coerce - convert string inputs to correct types ----
const querySchema = z.object({
  page: z.coerce.number().min(1).default(1),
  limit: z.coerce.number().min(1).max(100).default(20),
  active: z.coerce.boolean().default(false),
});
// z.coerce converts: '2' โ†’ 2, '1' or 'true' โ†’ true

Tip

Tip

Practice Zod Schema Validation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for Zod Schema Validation

Practice Task

Note

Practice Task - (1) Write a working example of Zod Schema Validation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Zod Schema Validation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done