zod-validation-patterns
БесплатноБез исполняемых скриптовНе проверенThis skill provides comprehensive patterns for using Zod validation library in TypeScript applications. It ensures input validation is done correctly…
Об этом скилле
Zod Validation Patterns Skill
Use this skill when: Working with user input validation, API request validation, form data validation, or data transformation in Quetrex.
Purpose
This skill provides comprehensive patterns for using Zod validation library in TypeScript applications. It ensures input validation is done correctly, securely, and consistently across the codebase.
What's Covered
Schema Patterns - Complete guide to all Zod schema types
- Primitives (string, number, boolean, date)
- Collections (array, object, map, set, record)
- Advanced types (union, intersection, discriminated unions)
- Optional/nullable patterns
- Branded types and recursive schemas
Error Handling - Robust error management
- Custom error messages
- Internationalization (i18n)
- Error formatting for UI display
- Safe parsing patterns
- Error recovery strategies
Refinements - Custom validation logic
- Basic and chained refinements
- Cross-field validation
- Conditional validation
- Business logic validation
- File upload validation
Transforms - Data transformation and normalization
- Type coercion
- Data cleaning and normalization
- Computed fields
- Preprocessing patterns
Async Validation - Asynchronous validation patterns
- Database uniqueness checks
- API validations
- Concurrent async validations
- Error handling and timeouts
Type Inference - TypeScript type extraction
- z.infer patterns
- Input vs output types
- Generic schema types
- Discriminated union inference
API Integration - Next.js integration patterns
- API routes validation
- Server Actions validation
- Form data and file uploads
- Error response formatting
Common Schemas - Reusable schema library
- Email, password, phone validation
- URL, UUID, date schemas
- Address, credit card validation
- Username, slug, color schemas
Quick Start
Basic Usage
import { z } from 'zod'
// Define schema
const userSchema = z.object({
email: z.string().email(),
age: z.number().int().positive(),
role: z.enum(['admin', 'user'])
})
// Parse data (throws on error)
const user = userSchema.parse(data)
// Safe parse (returns result object)
const result = userSchema.safeParse(data)
if (result.success) {
console.log(result.data)
} else {
console.error(result.error)
}
Type Inference
// Extract TypeScript type from schema
type User = z.infer<typeof userSchema>
// { email: string; age: number; role: 'admin' | 'user' }
API Route Example
// src/app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
const createUserSchema = z.object({
email: z.string().email(),
password: z.string().min(8)
})
export async function POST(request: NextRequest) {
const body = await request.json()
const result = createUserSchema.safeParse(body)
if (!result.success) {
return NextResponse.json(
{ error: 'Validation failed', details: result.error.format() },
{ status: 400 }
)
}
// Process validated data
const { email, password } = result.data
// ...
}
When to Use This Skill
DO Use for:
- API request validation - All incoming data to API routes
- Form submission validation - Client and server-side
- Database input validation - Before inserting/updating
- Configuration validation - Environment variables, config files
- File upload validation - Size, type, content validation
- External API responses - Validate third-party data
DON'T Use for:
- Simple type checks - Use TypeScript types when validation isn't needed
- Runtime performance-critical paths - Validation has overhead
- Already validated data - Don't re-validate trusted internal data
Best Practices
- Validate at boundaries - API routes, Server Actions, external data sources
- Use safe parsing - Prefer
safeParse()overparse()for better error handling - Provide clear error messages - Customize messages for user-facing validation
- Reuse common schemas - Use schemas from
common-schemas.md - Type inference - Always use
z.infer<typeof schema>for TypeScript types - Test edge cases - Write tests for validation logic
- Document complex schemas - Add JSDoc comments for business rules
Common Patterns
1. Optional Fields with Defaults
const configSchema = z.object({
timeout: z.number().int().positive().default(30),
retries: z.number().int().min(0).default(3),
debug: z.boolean().optional()
})
2. Conditional Required Fields
const addressSchema = z.object({
country: z.string(),
state: z.string().o
Установить zod-validation-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл zod-validation-patterns?
This skill provides comprehensive patterns for using Zod validation library in TypeScript applications. It ensures input validation is done correctly, securely, and consistently across the codebase.
Как установить скилл zod-validation-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл zod-validation-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic