Zod Input Validation
Define and validate data schemas with Zod for type-safe input validation in TypeScript applications.
Overview
The library supports all JavaScript primitives plus complex types like objects, arrays, unions, intersections, tuples, records, maps, and sets. It provides built-in validators for common patterns like email, URL, UUID, CUID, regex, and numeric ranges. Transform functions allow you to coerce and modify data during parsing, while refinements let you add custom validation logic.
Zod integrates with popular frameworks and libraries including React Hook Form, tRPC, Astro, Next.js, and Hono. For API input validation, Zod schemas can validate request bodies, query parameters, and path parameters, returning detailed error messages with the exact path to invalid fields. The `.safeParse()` method provides non-throwing validation, returning a discriminated union of success or error results.
Who Is This For?
- Validate API request bodies with detailed error messages
- Define form schemas with React Hook Form integration
- Parse and transform environment variables at startup
- Create reusable validation schemas for shared data models
Installation
npm install zod Configuration
import { z } from "zod"
const UserSchema = z.object({
name: z.string().min(2).max(100),
email: z.string().email(),
age: z.number().int().positive().optional(),
role: z.enum(["admin", "user", "moderator"]),
})
type User = z.infer<typeof UserSchema>
const result = UserSchema.safeParse(requestBody)
if (!result.success) {
return res.status(400).json({ errors: result.error.issues })
} Explore AI Tools
Discover the best AI tools that complement your skills
Read AI & Design Articles
Tips and trends in the world of design and AI
Related Servers
Snyk Security Scan
Detect vulnerabilities in your dependencies and application code. Get actionable remediation advice and automatic fix pull requests.
SonarQube Code Quality
Run continuous code quality and security analysis to catch bugs, code smells, and vulnerabilities before they reach production.
OWASP ZAP Security Testing
Perform automated web application security testing to find common vulnerabilities like XSS, injection flaws, and misconfigurations.