typescript

Zod Schema Validation

Type-safe runtime validation with Zod for TypeScript

Tarun Sharma
Tarun SharmaJanuary 15, 2024 ยท 1 min read ยท Last Updated:
import { z } from 'zod';

const UserSchema = z.object({
  id: z.number(),
  name: z.string().min(2).max(50),
  email: z.string().email(),
  age: z.number().min(18).optional(),
  role: z.enum(['admin', 'user', 'guest']),
  createdAt: z.string().datetime(),
});

type User = z.infer<typeof UserSchema>;

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

API Request Validation

const CreateUserSchema = UserSchema.omit({ id: true, createdAt: true });
const UpdateUserSchema = CreateUserSchema.partial();

// In Express/NestJS handler
const validated = CreateUserSchema.parse(req.body); // Throws on invalid

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Full-stack developer and tech educator with 10+ years of experience building scalable applications. Passionate about Node.js, NestJS, React, and cloud technologies. Creator of 50+ courses on Udemy and active YouTube educator helping developers level up their skills.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16