Zod Schema Validation Skill
Build type-safe runtime validation with Zod for APIs, forms, and data pipelines with TypeScript 5.5+ integration and automatic type inference.
Open the source and read safety notes before installing.
Prerequisites
- TypeScript 5.0+ (5.5+ recommended)
- zod ^3.22.0
- Node.js 18+ or modern browser
- Basic TypeScript knowledge
- TypeScript 4.5+ (recommended 5.0+) for full type inference and compile-time type safety with Zod schemas
- Runtime environment: Node.js 18+ for server-side validation or modern browser with ES2020+ support for client-side validation
Schema details
- Install type
- package
- Reading time
- 6 min
- Difficulty score
- 100
- Troubleshooting
- Yes
- Breaking changes
- No
- Download URL
- /downloads/skills/zod-schema-validator.zip
- Package verified
- Yes
- SHA-256
- 56133067087d163b8ff5a35aa325a55b75ce8916a75bfc7523075b5e3e76974f
- Skill type
- general
- Skill level
- advanced
- Verification
- draft
- Verified at
- 2025-10-16
| Platform | Support | Install path |
|---|---|---|
| claude-code | Native | .claude/skills/<skill-name>/SKILL.md |
| codex | Native | .agents/skills/<skill-name>/SKILL.md |
| windsurf | Native | .windsurf/skills/<skill-name>/SKILL.md |
| gemini | Native | .gemini/skills/<skill-name>/SKILL.md or .agents/skills/<skill-name>/SKILL.md |
| cursor | Adapter | .cursor/rules/<skill-name>.mdc |
| cli | Manual | AGENTS.md or tool-specific context file |
Full copyable content
import { z } from 'zod';
const passwordSchema = z
.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[0-9]/, 'Password must contain a number')
.regex(/[^a-zA-Z0-9]/, 'Password must contain a special character');
const userRegistrationSchema = z.object({
email: z.string().email('Invalid email address'),
password: passwordSchema,
confirmPassword: z.string(),
age: z.number().int().min(18, 'Must be 18 or older').max(100),
phone: z.string().regex(/^\\+?[1-9]\\d{1,14}$/).optional(),
acceptTerms: z.literal(true, {
errorMap: () => ({ message: 'You must accept the terms' }),
}),
}).refine((data) => data.password === data.confirmPassword, {
message: 'Passwords do not match',
path: ['confirmPassword'],
});
type UserRegistration = z.infer<typeof userRegistrationSchema>;
// Usage with safeParse for error handling
const result = userRegistrationSchema.safeParse({
email: 'user@example.com',
password: 'SecureP@ss1',
confirmPassword: 'SecureP@ss1',
age: 25,
acceptTerms: true,
});
if (!result.success) {
console.error(result.error.format());
} else {
console.log('Valid user:', result.data);
}About this resource
Build type-safe runtime validation with Zod for APIs, forms, and data pipelines with TypeScript 5.5+ integration and automatic type inference. Zod is a TypeScript-first schema validation library that provides runtime validation matching compile-time types, enabling you to validate untrusted data (API inputs, user forms, external integrations) while maintaining end-to-end type safety. With zero dependencies, 8kb minified bundle size, and automatic type inference, Zod eliminates the gap between static types and runtime reality. Features include composable schemas with .extend() and .merge(), custom validation with .refine() and async support, discriminated unions for efficient type narrowing, transforms for data coercion, and seamless integration with React Hook Form, tRPC, and Express.
Content
Zod Schema Validator Skill
What This Skill Enables
Claude can build comprehensive validation schemas using Zod, the TypeScript-first validation library tested against TypeScript v5.5+. Zod provides runtime validation that matches compile-time types, enabling you to validate untrusted data (API inputs, user forms, external integrations) while maintaining end-to-end type safety. With zero dependencies and automatic type inference, Zod eliminates the gap between static types and runtime reality.
Compatibility
Native
- Claude Code / Claude: native skill usage via
SKILL.md. - Codex/OpenAI workflows: compatible with Agent Skills-style
SKILL.mdcontent as reusable workflow instructions.
Manual Adaptation
- Gemini CLI: native skill usage via
.gemini/skills/<skill-name>/SKILL.mdor.agents/skills/<skill-name>/SKILL.mdwhere supported. - Cursor: use the generated
.cursor/rules/*.mdcadapter for project rules. - OpenClaw and similar agents: use the same skill content as a reusable prompt/workflow file when native skill import is unavailable.
Prerequisites
Required:
- Claude Pro subscription or Claude Code CLI
- TypeScript 5.0+ (5.5+ recommended)
- Node.js 18+ or modern browser
- Basic TypeScript knowledge
What Claude handles automatically:
- Writing Zod schemas with proper validators
- Inferring TypeScript types from schemas
- Adding custom validation logic with refinements
- Generating error messages in multiple formats
- Creating reusable schema compositions
- Implementing async validation
- Adding transforms for data coercion
- Integrating with React Hook Form or tRPC
How to Use This Skill
Basic Schema Creation
Prompt: "Create Zod schemas for a user registration API that validates email, password (min 8 chars, requires number and special char), age (18-100), and optional phone number."
Claude will:
- Write Zod schema with proper validators
- Add regex patterns for email and password
- Include range validation for age
- Make phone number optional
- Generate custom error messages
- Infer TypeScript type from schema
- Show validation usage examples
Form Validation with React Hook Form
Prompt: "Build a React form with Zod validation for: name, email, address (street, city, state, zip), and checkbox for terms acceptance. Integrate with React Hook Form and show field-level errors."
Claude will:
- Create nested Zod schema for address
- Set up React Hook Form with zodResolver
- Add real-time validation on blur
- Display error messages per field
- Prevent submission until valid
- Include TypeScript types
- Add accessible error announcements
API Request/Response Validation
Prompt: "Create Zod schemas for a REST API with request validation and response parsing. Include pagination parameters, filters, and error handling."
Claude will:
- Define request body schemas
- Create query parameter validators
- Add response schema with safeParse
- Handle validation errors gracefully
- Include pagination metadata
- Add discriminated unions for responses
- Generate OpenAPI types from schemas
Complex Business Logic Validation
Prompt: "Build a Zod schema for order validation where: if payment method is 'credit_card', require card details; if 'paypal', require email; shipping date must be after today; total must match items sum."
Claude will:
- Use discriminated unions for payment methods
- Add conditional validation with refine()
- Implement cross-field validation
- Calculate and validate totals
- Add date comparison logic
- Provide clear error paths
- Include async validation for external checks
Tips for Best Results
Infer Types, Don't Duplicate: Always use
z.infer<typeof schema>instead of defining types manually. This ensures runtime validation matches compile-time types.Use
.safeParse()for Untrusted Data: In API routes or external inputs, usesafeParse()instead ofparse()to avoid throwing exceptions. Handle validation errors gracefully.Custom Error Messages: Request custom error messages with
.min(8, { message: 'Password must be at least 8 characters' })for better UX.Refinements for Complex Logic: Use
.refine()or.superRefine()for validation that involves multiple fields or external calls.Reusable Schemas: Create base schemas and extend them with
.extend()or compose with.merge()to avoid duplication.Transforms for Coercion: Use
.transform()to normalize data (trim strings, parse numbers) before validation.
Common Workflows
E-Commerce Checkout Validation
"Create complete Zod validation for checkout flow:
1. Customer info: email, phone, billing address
2. Shipping: address with validation (can't be PO box), preferred delivery date
3. Payment: discriminated union for credit card, PayPal, crypto
4. Items: array of products with quantity (min 1, max 10), size, color
5. Promo code: optional, alphanumeric, validate against API
6. Total must match cart calculation
7. Accept terms and conditions (required)"
API Gateway Validation Layer
"Build API validation middleware with Zod:
1. Validate request headers (auth token, content-type)
2. Parse and validate query parameters with coercion
3. Validate request body based on endpoint
4. Add rate limiting metadata validation
5. Validate response format before sending to client
6. Log validation errors with request context
7. Return standardized error responses"
Database Input Sanitization
"Create Zod schemas for database operations:
1. User input sanitization before INSERT
2. Strip dangerous characters from strings
3. Validate foreign key relationships exist
4. Ensure email uniqueness with async validator
5. Transform dates to ISO format
6. Validate JSON columns match expected structure
7. Add database constraint validation"
File Upload Validation
"Build file upload validator with Zod:
1. Validate MIME types (images: PNG, JPG, WebP)
2. Check file size (max 5MB)
3. Validate image dimensions (min 800x600, max 4000x4000)
4. Sanitize filename (alphanumeric, hyphens, underscores)
5. Validate metadata (EXIF data)
6. Check for malware signatures
7. Transform to standard format"
Troubleshooting
Issue: Type inference not working
Solution: Ensure TypeScript version is 5.0+. Use z.infer<typeof schema> correctly. Check tsconfig.json has strict: true. Update Zod to latest version.
Issue: Validation errors not showing custom messages
Solution: Add message parameter to validators: .min(8, { message: '...' }). Use error.format() to get structured errors. Check error path matches form field names.
Issue: Async validation not working
Solution: Use .refine() with async function, not .transform(). Ensure you await the parse result. Consider using .parseAsync() or .safeParseAsync().
Issue: Performance slow with large arrays
Solution: Use .nonempty() instead of .min(1) for faster validation. Implement pagination. Consider lazy validation with .lazy() for recursive structures.
Issue: Optional fields not working correctly
Solution: Use .optional() for truly optional fields, .nullable() for null values, .default() for default values. Don't mix .optional() with .nullable() unless you mean to accept both.
Issue: Union types confusing in errors
Solution: Use discriminated unions with .discriminatedUnion() for better error messages. Add explicit type checking before validation. Provide user-friendly labels.
Learn More
- Zod Official Documentation
- Zod GitHub Repository
- React Hook Form + Zod Integration
- tRPC + Zod Guide
- Zod to JSON Schema
- Zod Error Formatting
Features
- TypeScript-first with automatic type inference using z.infer for end-to-end type safety
- Zero dependencies with 8kb minified bundle size for minimal overhead in production applications
- Composable schemas with .extend() and .merge() for reusable validation patterns and schema composition
- Custom validation with .refine() and .superRefine() for complex business logic and cross-field validation
- Async validation support with .parseAsync() and .safeParseAsync() for database checks and external API calls
- Discriminated unions with z.discriminatedUnion() for efficient type narrowing and better error messages
- Data transformation with .transform() for coercion, normalization, and type conversion before validation
- Error handling with .safeParse() returning discriminated union results without throwing exceptions
Use Cases
- API request/response validation with type-safe parsing and error handling for REST and GraphQL endpoints
- Form validation with error messages integrated with React Hook Form, Formik, and native HTML forms
- Database input sanitization and validation before INSERT/UPDATE operations with Prisma integration
- Configuration validation for environment variables and application settings with type safety
- Data pipeline validation for ETL processes, CSV parsing, and data transformation workflows
- Type-safe API client generation from OpenAPI specifications with Zod schema validation
- Content
- What This Skill Enables
- Compatibility
- Native
- Manual Adaptation
- Prerequisites
- How to Use This Skill
- Basic Schema Creation
- Form Validation with React Hook Form
- API Request/Response Validation
- Complex Business Logic Validation
- Tips for Best Results
- Common Workflows
- E-Commerce Checkout Validation
- API Gateway Validation Layer
- Database Input Sanitization
Source citations
Signals
Loading live community signals…
A short, calm digest of reviewed Claude resources. Unsubscribe any time.