惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
H
Help Net Security
小众软件
小众软件
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
Apple Machine Learning Research
Apple Machine Learning Research
S
SegmentFault 最新的问题
Last Week in AI
Last Week in AI
爱范儿
爱范儿
量子位
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
博客园 - 【当耐特】
V
Visual Studio Blog
大猫的无限游戏
大猫的无限游戏
博客园_首页
Jina AI
Jina AI
D
Docker
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Microsoft Security Blog
Microsoft Security Blog
阮一峰的网络日志
阮一峰的网络日志

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Zod Validation: Type-Safe APIs & Forms in TypeScript (Com...
Anup Karanjk · 2026-05-22 · via DEV Community

TypeScript types disappear at runtime. Your carefully typed User interface means nothing when the JSON from an external API, a form submission, or a database query arrives as unknown. Zod bridges this gap: you define a schema once, validate data against it at runtime, and get a TypeScript type back for free. This guide covers every Zod pattern you will use — from basic schemas to API validation, form handling, and OpenAPI generation.

If you are building TypeScript APIs or form-heavy applications, browse WOWHOW Tools for starter kits and check out the full catalog for Next.js and React templates with validation built in.

Why Zod Over Alternatives

Zod infers TypeScript types from schemas (schema-first, not type-first). It has zero dependencies, works in Node.js and browsers, and its error messages are structured objects you can use to build user-facing form errors without any extra work. It also chains neatly with transforms — parse, validate, and reshape data in one step.

Core Schema Types

import { z } from 'zod'

// primitives
const name    = z.string()
const age     = z.number()
const active  = z.boolean()
const created = z.date()
const id      = z.bigint()

// string constraints
const email    = z.string().email()
const url      = z.string().url()
const uuid     = z.string().uuid()
const slug     = z.string().regex(/^[a-z0-9-]+$/, 'Lowercase letters, numbers, hyphens only')
const password = z.string().min(8).max(128)
const bio      = z.string().max(500).optional()

// number constraints
const price    = z.number().positive().finite()
const rating   = z.number().int().min(1).max(5)
const quantity = z.number().int().nonnegative()

// literals and enums
const role     = z.enum(['admin', 'editor', 'viewer'])
const status   = z.literal('active')
const exact    = z.union([z.literal('pending'), z.literal('shipped'), z.literal('delivered')])

// infer types automatically
type Role   = z.infer   // 'admin' | 'editor' | 'viewer'
type Email  = z.infer  // string (with runtime guarantee)

Enter fullscreen mode Exit fullscreen mode

Object Schemas

const UserSchema = z.object({
  id:         z.string().uuid(),
  email:      z.string().email().toLowerCase(),  // transform to lowercase
  firstName:  z.string().min(1).max(50),
  lastName:   z.string().min(1).max(50),
  role:       z.enum(['admin', 'editor', 'viewer']).default('viewer'),
  age:        z.number().int().min(13).max(120).optional(),
  createdAt:  z.string().datetime(),  // ISO 8601 string
})

type User = z.infer

// parse: throws ZodError on failure
const user = UserSchema.parse(rawData)

// safeParse: returns { success, data } or { success, error }
const result = UserSchema.safeParse(rawData)
if (!result.success) {
  console.error(result.error.flatten())
  // { fieldErrors: { email: ['Invalid email'] }, formErrors: [] }
}

Enter fullscreen mode Exit fullscreen mode

Nested Objects and Arrays

const AddressSchema = z.object({
  street:  z.string().min(1),
  city:    z.string().min(1),
  state:   z.string().length(2),
  zipCode: z.string().regex(/^d{5}(-d{4})?$/),
  country: z.string().length(2).default('US'),
})

const OrderSchema = z.object({
  id:          z.string().uuid(),
  customerId:  z.string().uuid(),
  items:       z.array(
    z.object({
      productId: z.string().uuid(),
      quantity:  z.number().int().positive(),
      unitPrice: z.number().positive(),
    })
  ).min(1, 'Order must have at least one item'),
  shippingAddress: AddressSchema,
  total:       z.number().positive(),
  status:      z.enum(['pending', 'confirmed', 'shipped', 'delivered', 'cancelled']),
  notes:       z.string().max(1000).nullable().default(null),
})

type Order = z.infer

// tuple with mixed types
const CoordSchema = z.tuple([z.number(), z.number()])  // [lat, lng]
const TripleSchema = z.tuple([z.string(), z.number(), z.boolean()])

Enter fullscreen mode Exit fullscreen mode

Transforms: Parse and Reshape in One Step

// coerce strings from form inputs
const FormPriceSchema = z
  .string()
  .transform((val) => parseFloat(val))
  .pipe(z.number().positive())

// parse ISO date strings into Date objects
const DateFromStringSchema = z
  .string()
  .datetime()
  .transform((str) => new Date(str))

// normalize phone numbers
const PhoneSchema = z
  .string()
  .transform((val) => val.replace(/[^0-9]/g, ''))
  .pipe(z.string().length(10, 'Must be 10 digits'))

// computed fields using transform
const FullNameSchema = z
  .object({
    firstName: z.string(),
    lastName:  z.string(),
  })
  .transform((data) => ({
    ...data,
    fullName: `\${data.firstName} \${data.lastName}`,
    initials: `\${data.firstName[0]}.\${data.lastName[0]}.`,
  }))

const { firstName, lastName, fullName, initials } = FullNameSchema.parse({
  firstName: 'Anup',
  lastName:  'Karanjkar',
})
// fullName: 'Anup Karanjkar', initials: 'A.K.'

Enter fullscreen mode Exit fullscreen mode

Refinements: Cross-Field and Async Validation

// single-field refinement
const PasswordSchema = z
  .string()
  .min(8)
  .refine(
    (val) => /[A-Z]/.test(val) && /[0-9]/.test(val) && /[^a-zA-Z0-9]/.test(val),
    { message: 'Password must contain uppercase, number, and special character' }
  )

// cross-field refinement
const PasswordConfirmSchema = z
  .object({
    password:        z.string().min(8),
    confirmPassword: z.string(),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: 'Passwords do not match',
    path: ['confirmPassword'],   // attach error to specific field
  })

// date range validation
const DateRangeSchema = z
  .object({
    startDate: z.string().date(),
    endDate:   z.string().date(),
  })
  .refine(
    (data) => new Date(data.endDate) > new Date(data.startDate),
    { message: 'End date must be after start date', path: ['endDate'] }
  )

// async refinement (e.g. database uniqueness check)
const UniqueEmailSchema = z
  .string()
  .email()
  .superRefine(async (email, ctx) => {
    const exists = await db.user.findUnique({ where: { email } })
    if (exists) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'Email already in use',
      })
    }
  })

// use parseAsync for schemas with async refinements
const validEmail = await UniqueEmailSchema.parseAsync('user@example.com')

Enter fullscreen mode Exit fullscreen mode

API Request Validation in Next.js Route Handlers

import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'

const CreateProductSchema = z.object({
  name:        z.string().min(3).max(100),
  price:       z.number().positive(),
  currency:    z.enum(['USD', 'INR', 'EUR']).default('USD'),
  description: z.string().min(10).max(5000),
  tags:        z.array(z.string()).max(10).default([]),
  published:   z.boolean().default(false),
})

type CreateProductInput = z.infer

export async function POST(req: NextRequest) {
  let body: unknown
  try {
    body = await req.json()
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
  }

  const result = CreateProductSchema.safeParse(body)
  if (!result.success) {
    return NextResponse.json(
      {
        error: 'Validation failed',
        details: result.error.flatten().fieldErrors,
      },
      { status: 422 }
    )
  }

  const product = await createProduct(result.data)
  return NextResponse.json(product, { status: 201 })
}

// helper to validate any route handler input
function validateBody(schema: z.ZodType) {
  return async (req: NextRequest): Promise => {
    let body: unknown
    try {
      body = await req.json()
    } catch {
      return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
    }
    const result = schema.safeParse(body)
    if (!result.success) {
      return NextResponse.json(
        { error: 'Validation failed', details: result.error.flatten().fieldErrors },
        { status: 422 }
      )
    }
    return { data: result.data }
  }
}

Enter fullscreen mode Exit fullscreen mode

Form Validation with React Hook Form

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'

const CheckoutSchema = z.object({
  email:     z.string().email('Enter a valid email'),
  firstName: z.string().min(1, 'Required').max(50),
  lastName:  z.string().min(1, 'Required').max(50),
  address:   z.string().min(5, 'Enter full address'),
  city:      z.string().min(1, 'Required'),
  pinCode:   z.string().regex(/^d{6}$/, 'Enter 6-digit PIN code'),
  phone:     z.string().regex(/^[6-9]d{9}$/, 'Enter valid Indian mobile number'),
})

type CheckoutFormData = z.infer

function CheckoutForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm({
    resolver: zodResolver(CheckoutSchema),
  })

  const onSubmit = async (data: CheckoutFormData) => {
    // data is fully typed AND validated
    await submitOrder(data)
  }

  return (


      {errors.email && 
{errors.email.message}
}


      {errors.pinCode && 
{errors.pinCode.message}
}


        {isSubmitting ? 'Processing...' : 'Place Order'}


  )
}

Enter fullscreen mode Exit fullscreen mode

Schema Composition and Reuse

// base schema — shared fields
const TimestampedSchema = z.object({
  createdAt: z.string().datetime(),
  updatedAt: z.string().datetime(),
})

const BaseEntitySchema = z.object({
  id: z.string().uuid(),
}).merge(TimestampedSchema)

// extend for specific entities
const ProductSchema = BaseEntitySchema.extend({
  name:  z.string(),
  price: z.number().positive(),
})

// pick/omit for partial schemas
const ProductPreviewSchema = ProductSchema.pick({ id: true, name: true })
const CreateProductInput   = ProductSchema.omit({ id: true, createdAt: true, updatedAt: true })
const UpdateProductInput   = CreateProductInput.partial()  // all fields optional

// discriminated unions
const ApiResponseSchema = z.discriminatedUnion('success', [
  z.object({ success: z.literal(true),  data: z.unknown() }),
  z.object({ success: z.literal(false), error: z.string(), code: z.number() }),
])

type ApiResponse = z.infer

Enter fullscreen mode Exit fullscreen mode

Environment Variable Validation

// src/env.ts — validate at startup, not at request time
import { z } from 'zod'

const EnvSchema = z.object({
  NODE_ENV:        z.enum(['development', 'test', 'production']),
  DATABASE_URL:    z.string().url(),
  REDIS_URL:       z.string().url().optional(),
  NEXTAUTH_SECRET: z.string().min(32),
  RAZORPAY_KEY_ID: z.string().startsWith('rzp_'),
  PORT:            z.coerce.number().int().positive().default(3000),
})

const parsed = EnvSchema.safeParse(process.env)
if (!parsed.success) {
  console.error('Invalid environment variables:')
  console.error(parsed.error.flatten().fieldErrors)
  process.exit(1)
}

export const env = parsed.data
// env.PORT is typed as number, env.DATABASE_URL is typed as string

Enter fullscreen mode Exit fullscreen mode

People Also Ask

What is the difference between parse and safeParse in Zod?

parse throws a ZodError if validation fails. Use it when you want the error to propagate up as an exception — common in server-side code where you have a top-level error handler. safeParse returns a discriminated union { success: true, data } | { success: false, error }. Use it when you need to handle validation failure gracefully without exceptions — typical for API request validation and form handling where you want to return structured error messages.

Can Zod schemas generate OpenAPI / JSON Schema documentation?

Yes, via the zod-to-json-schema package (npm install zod-to-json-schema). Call zodToJsonSchema(MySchema) to get a JSON Schema object you can plug into Swagger UI or any OpenAPI toolchain. For full OpenAPI 3.x spec generation, @asteasolutions/zod-to-openapi provides a registry-based API that produces complete path definitions including request bodies, query params, and response schemas.

How do I handle validation errors in a way that maps to form field errors?

Use error.flatten() on the ZodError. It returns { fieldErrors: Record<string, string[]>, formErrors: string[] }. Field errors are keyed by the field path (e.g., { email: ['Invalid email address'] }). If you are using React Hook Form with zodResolver, this mapping happens automatically — the resolver converts Zod errors into React Hook Form's error format and populates formState.errors for you.

Originally published at wowhow.cloud