Programming 1 min read 1,117 views

Zod: TypeScript-First Schema Validation for Modern Applications

Zod has become the standard for runtime validation in TypeScript. Learn patterns for forms, APIs, and more.

E
Zod validation code

Zod is the leading TypeScript-first schema validation library, providing runtime validation with full type inference.

Basic Usage

import { z } from "zod";

// Define schema
const UserSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  age: z.number().min(18).optional(),
});

// Infer TypeScript type
type User = z.infer<typeof UserSchema>;

// Validate data
const result = UserSchema.safeParse(input);
if (result.success) {
  console.log(result.data); // Typed as User
} else {
  console.log(result.error.issues);
}

Advanced Patterns

// Transform data
const DateSchema = z.string().transform((str) => new Date(str));

// Custom validation
const PasswordSchema = z.string()
  .min(8)
  .refine((val) => /[A-Z]/.test(val), "Must contain uppercase")
  .refine((val) => /[0-9]/.test(val), "Must contain number");

// Discriminated unions
const ResponseSchema = z.discriminatedUnion("status", [
  z.object({ status: z.literal("success"), data: z.any() }),
  z.object({ status: z.literal("error"), message: z.string() }),
]);

Form Validation

Use with React Hook Form or other form libraries for seamless validation.

Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!