zod-validation-expert
Expert in Zod — TypeScript-first schema validation. Covers parsing, custom errors, refinements, type inference, and integration with React Hook Form, Next.js, and tRPC.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 3.3w
- Forks
- 3.9k
01 前言 Front Matter
- name
- zod-validation-expert
- metadata
- { "risk": "safe", "source": "community", "date_added": "2026-03-05" }
- description
- Expert in Zod — TypeScript-first schema validation. Covers parsing, custom errors, refinements, type inference, and integration with React Hook Form, Next.js, and tRPC.
02 资源文件 58
- 参考文档docx-js.md16.1 KB
- 许可证LICENSE.txt1.4 KB
- 参考文档ooxml.md23.0 KB
- 参考文档ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd1.9 KB
- 参考文档ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd2.5 KB
- 参考文档ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd2.8 KB
- 参考文档ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd1.3 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd73.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd6.8 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd50.1 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd624 B
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd148.5 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd1.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd8.7 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd14.4 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd81.7 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd1.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd7.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd6.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd1.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd880 B
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd2.5 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd3.4 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd7.3 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd22.8 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd1.3 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd236.6 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd25.5 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd24.7 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd535 B
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd5.6 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd3.9 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd167.4 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd4.5 KB
- 参考文档ooxml/schemas/mce/mc.xsd3.1 KB
- 参考文档ooxml/schemas/microsoft/wml-2010.xsd25.9 KB
- 参考文档ooxml/schemas/microsoft/wml-2012.xsd3.7 KB
- 参考文档ooxml/schemas/microsoft/wml-2018.xsd901 B
- 参考文档ooxml/schemas/microsoft/wml-cex-2018.xsd1.7 KB
- 参考文档ooxml/schemas/microsoft/wml-cid-2016.xsd1002 B
- 参考文档ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd600 B
- 参考文档ooxml/schemas/microsoft/wml-symex-2015.xsd745 B
- 脚本ooxml/scripts/pack.py5.5 KB
- 脚本ooxml/scripts/unpack.py1.0 KB
- 脚本ooxml/scripts/validate.py1.9 KB
- 脚本ooxml/scripts/validation/__init__.py336 B
- 脚本ooxml/scripts/validation/base.py39.0 KB
- 脚本ooxml/scripts/validation/docx.py9.8 KB
- 脚本ooxml/scripts/validation/pptx.py12.0 KB
- 脚本ooxml/scripts/validation/redlining.py10.9 KB
- 脚本scripts/__init__.py65 B
- 脚本scripts/document.py49.2 KB
- 脚本scripts/templates/comments.xml2.6 KB
- 脚本scripts/templates/commentsExtended.xml2.6 KB
- 脚本scripts/templates/commentsExtensible.xml2.7 KB
- 脚本scripts/templates/commentsIds.xml2.6 KB
- 脚本scripts/templates/people.xml147 B
- 脚本scripts/utilities.py13.4 KB
03 SKILL.md 正文
Zod Validation Expert
You are a production-grade Zod expert. You help developers build type-safe schema definitions and validation logic. You master Zod fundamentals (primitives, objects, arrays, records), type inference (z.infer), complex validations (.refine, .superRefine), transformations (.transform), and integrations across the modern TypeScript ecosystem (React Hook Form, Next.js API Routes / App Router Actions, tRPC, and environment variables).
When to Use This Skill
- Use when defining TypeScript validation schemas for API inputs or forms
- Use when setting up environment variable validation (
process.env) - Use when integrating Zod with React Hook Form (
@hookform/resolvers/zod) - Use when extracting or inferring TypeScript types from runtime validation schemas
- Use when writing complex validation rules (e.g., cross-field validation, async validation)
- Use when transforming input data (e.g., string to Date, string to number coercion)
- Use when standardizing error message formatting
Core Concepts
Why Zod?
Zod eliminates the duplication of writing a TypeScript interface and a runtime validation schema. You define the schema once, and Zod infers the static TypeScript type. Note that Zod is for parsing, not just validation. safeParse and parse return clean, typed data, stripping out unknown keys by default.
Schema Definition & Inference
Primitives & Coercion
import { z } from "zod";
// Basic primitives
const stringSchema = z.string().min(3).max(255);
const numberSchema = z.number().int().positive();
const dateSchema = z.date();
// Coercion (automatically casting inputs before validation)
// Highly useful for FormData in Next.js Server Actions or URL queries
const ageSchema = z.coerce.number().min(18); // "18" -> 18
const activeSchema = z.coerce.boolean(); // "true" -> true
const dobSchema = z.coerce.date(); // "2020-01-01" -> Date object
Objects & Type Inference
const UserSchema = z.object({
id: z.string().uuid(),
username: z.string().min(3).max(20),
email: z.string().email(),
role: z.enum(["ADMIN", "USER", "GUEST"]).default("USER"),
age: z.number().min(18).optional(), // Can be omitted
website: z.string().url().nullable(), // Can be null
tags: z.array(z.string()).min(1), // Array with at least 1 item
});
// Infer the TypeScript type directly from the schema
// No need to write a separate `interface User { ... }`
export type User = z.infer<typeof UserSchema>;
Advanced Types
// Records (Objects with dynamic keys but specific value types)
const envSchema = z.record(z.string(), z.string()); // Record<string, string>
// Unions (OR)
const idSchema = z.union([z.string(), z.number()]); // string | number
// Or simpler:
const idSchema2 = z.string().or(z.number());
// Discriminated Unions (Type-safe switch cases)
const ActionSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("create"), id: z.string() }),
z.object({ type: z.literal("update"), id: z.string(), data: z.any() }),
z.object({ type: z.literal("delete"), id: z.string() }),
]);
Parsing & Validation
parse vs safeParse
const schema = z.string().email();
// ❌ parse: Throws a ZodError if validation fails
try {
const email = schema.parse("invalid-email");
} catch (err) {
if (err instanceof z.ZodError) {
console.error(err.issues);
}
}
// ✅ safeParse: Returns a result object (No try/catch needed)
const result = schema.safeParse("user@example.com");
if (!result.success) {
// TypeScript narrows result to SafeParseError
console.log(result.error.format());
// Early return or throw domain error
} else {
// TypeScript narrows result to SafeParseSuccess
const validEmail = result.data; // Type is `string`
}
Customizing Validation
Custom Error Messages
const passwordSchema = z.string()
.min(8, { message: "Password must be at least 8 characters long" })
.max(100, { message: "Password is too long" })
.regex(/[A-Z]/, { message: "Password must contain at least one uppercase letter" })
.regex(/[0-9]/, { message: "Password must contain at least one number" });
// Global custom error map (useful for i18n)
z.setErrorMap((issue, ctx) => {
if (issue.code === z.ZodIssueCode.invalid_type) {
if (issue.expected === "string") return { message: "This field must be text" };
}
return { message: ctx.defaultError };
});
Refinements (Custom Logic)
// Basic refinement
const passwordCheck = z.string().refine((val) => val !== "password123", {
message: "Password is too weak",
});
// Cross-field validation (e.g., password matching)
const formSchema = z.object({
password: z.string().min(8),
confirmPassword: z.string()
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"], // Sets the error on the specific field
});
Transformations
// Change data during parsing
const stringToNumber = z.string()
.transform((val) => parseInt(val, 10))
.refine((val) => !isNaN(val), { message: "Not a valid integer" });
// Now the inferred type is `number`, not `string`!
type TransformedResult = z.infer<typeof stringToNumber>; // number
Integration Patterns
React Hook Form
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const loginSchema = z.object({
email: z.string().email("Invalid email address"),
password: z.string().min(6, "Password must be 6+ characters"),
});
type LoginFormValues = z.infer<typeof loginSchema>;
export function LoginForm() {
const { register, handleSubmit, formState: { errors } } = useForm<LoginFormValues>({
resolver: zodResolver(loginSchema)
});
const onSubmit = (data: LoginFormValues) => {
// data is fully typed and validated
console.log(data.email, data.password);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email")} />
{errors.email && <span>{errors.email.message}</span>}
{/* ... */}
</form>
);
}
Next.js Server Actions
"use server";
import { z } from "zod";
// Coercion is critical here because FormData values are always strings
const createPostSchema = z.object({
title: z.string().min(3),
content: z.string().optional(),
published: z.coerce.boolean().default(false), // checkbox -> "on" -> true
});
export async function createPost(prevState: any, formData: FormData) {
// Convert FormData to standard object using Object.fromEntries
const rawData = Object.fromEntries(formData.entries());
const validatedFields = createPostSchema.safeParse(rawData);
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
};
}
// Proceed with validated database operation
const { title, content, published } = validatedFields.data;
// ...
return { success: true };
}
Environment Variables
// Make environment variables strictly typed and fail-fast
import { z } from "zod";
const envSchema = z.object({
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
PORT: z.coerce.number().default(3000),
API_KEY: z.string().min(10),
});
// Fails the build immediately if env vars are missing or invalid
const env = envSchema.parse(process.env);
export default env;
Best Practices
- ✅ Do: Co-locate schemas alongside the components or API routes that use them to maintain separation of concerns.
- ✅ Do: Use
z.infer<typeof Schema>everywhere instead of maintaining duplicate TypeScript interfaces manually. - ✅ Do: Prefer
safeParseoverparseto avoid scatteredtry/catchblocks and leverage TypeScript's control flow narrowing for robust error handling. - ✅ Do: Use
z.coercewhen accepting data fromURLSearchParamsorFormData, and be aware thatz.coerce.boolean()converts standard"false"/"off"strings unexpectedly without custom preprocessing. - ✅ Do: Use
.flatten()or.format()onZodErrorobjects to easily extract serializable, human-readable errors for frontend consumption. - ❌ Don't: Rely exclusively on
.partial()for update schemas if field types or constraints differ between creation and update operations; define distinct schemas instead. - ❌ Don't: Forget to pass the
pathoption in.refine()or.superRefine()when performing object-level cross-field validations, otherwise the error won't attach to the correct input field.
Troubleshooting
Problem: Type instantiation is excessively deep and possibly infinite.
Solution: This occurs with extreme schema recursion (e.g. deeply nested self-referential schemas). Use z.lazy(() => NodeSchema) for recursive structures and define the base TypeScript type explicitly instead of solely inferring it.
Problem: Empty strings pass validation when using .optional().
Solution: .optional() permits undefined, not empty strings. If an empty string means "no value," use .or(z.literal("")) or preprocess it: z.string().transform(v => v === "" ? undefined : v).optional().
04 同仓库更多 Skills
wealthville-pool-scoring
Score DeFi liquidity pools before providing liquidity. Returns a 0-100 pool score and an Enter/Hold/Exit/Reduce/Avoid verdict with calibrated confidence for ~68,800 Solana pools and 575 EVM pools, plus a public miss-inclusive track record. Use when asked whether a pool is worth LPing into, which pools look best right now, or how accurate the scores have actually been.
technical-debt-auditor
Scans a codebase and produces a quantified technical debt report with a prioritized remediation plan. Analyzes dead code, TODO/FIXME/HACK markers, dependency staleness, complexity hotspots, code duplication signals, test coverage gaps, unused exports, and outdated patterns. Use this skill when the user asks to audit their codebase for tech debt, wants a health check of their code quality, says things like "where should I focus refactoring", "find code smells", "audit my codebase", "what technical debt do we have", "prioritize cleanup work", or asks about code quality metrics. Also trigger when the user mentions "code rot", "legacy cleanup", "refactoring priorities", or wants to understand the overall health of a project before a major effort. Trigger even if the user doesn't say "technical debt" explicitly — any request to systematically assess code quality and identify improvement priorities belongs here.
readonly-sql-guard
Make an agent's database access provably read-only. Use when an agent runs caller-supplied SQL against a production/ERP/analytics database (a "query" MCP tool, text-to-SQL, an admin console), or when reviewing DB-access code for write/DDL/side-effect/transaction-escape risks. Checks what a statement CALLS, not just its shape.
web-artifacts-builder
Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts.
webapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
discernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.