zod
БесплатноБез исполняемых скриптовНе проверенZod TypeScript schema validation library for runtime type checking. USE WHEN: user mentions "Zod", "schema validation", "form validation", "API validation"…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Zod - Quick Reference
When to Use This Skill
- Form validation with React Hook Form
- API data parsing/validation
- Type inference from schemas
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:zodfor comprehensive documentation.
Essential Patterns
Basic Schema
import { z } from 'zod';
const userSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
age: z.number().min(18).optional(),
role: z.enum(['admin', 'user'])
});
// Type inference
type User = z.infer<typeof userSchema>;
// Parse
const user = userSchema.parse(data); // throws ZodError
const result = userSchema.safeParse(data); // { success, data/error }
Common Validations
// String
z.string().min(1).max(100).email().url().uuid()
// Number
z.number().int().positive().min(0).max(100)
// Custom validation
z.string().refine(val => val.startsWith('@'), "Must start with @")
// Object cross-field
z.object({
password: z.string(),
confirm: z.string()
}).refine(d => d.password === d.confirm, {
message: "Passwords don't match",
path: ['confirm']
});
React Hook Form
import { zodResolver } from '@hookform/resolvers/zod';
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: zodResolver(userSchema)
});
<input {...register('name')} />
{errors.name && <span>{errors.name.message}</span>}
Schema Operations
userSchema.partial() // All fields optional
userSchema.pick({ name: true }) // Pick fields
userSchema.omit({ id: true }) // Omit fields
userSchema.extend({ phone: z.string() }) // Extend
When NOT to Use This Skill
- Yup existing projects - Use
yupskill for Formik integration - NestJS DTOs - Use
class-validatorskill for decorator-based validation - Compile-time only checks - TypeScript types are sufficient
- Simple PropTypes - React PropTypes might be enough
Anti-Patterns to Avoid
- Do not define schemas inside components (performance)
- Do not use
.parse()for user input without try/catch - Do not forget custom error messages
Anti-Patterns
| Anti-Pattern | Why It's Bad | Correct Approach |
|---|---|---|
| Schema inside components | Re-created on every render | Define at module level |
| Using .parse() without try-catch | Throws unhandled errors | Use .safeParse() for user input |
| No custom error messages | Generic "Invalid input" | Add custom messages to all validations |
| Validating twice (FE + BE) | Performance waste | Share schemas between client/server |
| Not using z.infer | Manual type definitions | Always use type inference |
| Ignoring .transform() | Miss data normalization | Use transforms for trimming, etc. |
Quick Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| "Expected string, received number" | Type mismatch | Use z.coerce.string() for type coercion |
| Performance issues | Schema in component | Move schema to module level |
| Async validation not working | Using .parse() | Use .parseAsync() for async refinements |
| Nested errors not showing | Not using flatten() | Use error.flatten() for nested structures |
| "Invalid type" on optional fields | Using undefined | Use .optional() or .nullable() |
| Form not validating | Resolver not set | Add resolver: zodResolver(schema) |
Production Readiness
Error Handling
import { z, ZodError } from 'zod';
// Safe parsing with error handling
function validateInput<T>(schema: z.ZodSchema<T>, data: unknown): T {
const result = schema.safeParse(data);
if (!result.success) {
const errors = result.error.flatten();
throw new ValidationError(errors);
}
return result.data;
}
// Custom error messages
const userSchema = z.object({
email: z.string({
required_error: 'Email is required',
invalid_type_error: 'Email must be a string',
}).email({ message: 'Invalid email format' }),
password: z.string()
.min(8, { message: 'Password must be at least 8 characters' })
.regex(/[A-Z]/, { message: 'Password must contain uppercase letter' })
.regex(/[0-9]/, { message: 'Password must contain number' }),
});
// Error formatting for API responses
function formatZodError(error: ZodError): Record<string, string[]> {
return error.flatten().fieldErrors as Record<string, string[]>;
}
API Integration
// Express middleware
import { Request, Response, NextFunction } from 'express';
function validate<T extends z.ZodSchema>(schema: T) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({
code: 'VALIDATION_ERROR',
errors: formatZodError(result.error),
});
}
req.body = result.data;
next();
};
}
// Usage
app.post('/users', validate(createUserSchema), createUser);
// tRPC integration
export
Установить zod в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл zod?
Zod TypeScript schema validation library for runtime type checking. USE WHEN: user mentions "Zod", "schema validation", "form validation", "API validation", "type-safe validation", asks about "runtime validation", "React Hook Form validation" DO NOT USE FOR: Yup projects (use yup skill), class-validator/NestJS DTOs (use class-validator skill), PropTypes, compile-time only validation
Как установить скилл zod?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл zod запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic