zod-validation-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zod Validation Expert

Zod 验证专家

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).
你是一位生产级别的Zod专家,帮助开发者构建类型安全的Schema定义和验证逻辑。你精通Zod基础(基本类型、对象、数组、记录)、类型推断(
z.infer
)、复杂验证(
.refine
.superRefine
)、转换(
.transform
),以及与现代TypeScript生态系统的集成(React Hook Form、Next.js API路由/应用路由Actions、tRPC和环境变量)。

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
  • 为API输入或表单定义TypeScript验证Schema时使用
  • 设置环境变量验证(
    process.env
    )时使用
  • 将Zod与React Hook Form(
    @hookform/resolvers/zod
    )集成时使用
  • 从运行时验证Schema中提取或推断TypeScript类型时使用
  • 编写复杂验证规则(如跨字段验证、异步验证)时使用
  • 转换输入数据(如字符串转Date、字符串转数字强制转换)时使用
  • 标准化错误消息格式时使用

Core Concepts

核心概念

Why Zod?

为什么选择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.
Zod消除了重复编写TypeScript接口和运行时验证Schema的问题。你只需定义一次Schema,Zod就能推断出静态TypeScript类型。注意,Zod是用于解析,而非仅验证
safeParse
parse
会返回清晰的类型化数据,默认会剥离未知键。

Schema Definition & Inference

Schema定义与推断

Primitives & Coercion

基本类型与强制转换

typescript
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
typescript
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

对象与类型推断

typescript
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>;
typescript
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

高级类型

typescript
// 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() }),
]);
typescript
// 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

parse vs safeParse

typescript
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`
}
typescript
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

自定义错误消息

typescript
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 };
});
typescript
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)

细化验证(自定义逻辑)

typescript
// 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
});
typescript
// 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

转换

typescript
// 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
typescript
// 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

React Hook Form

typescript
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>
  );
}
typescript
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

Next.js Server Actions

typescript
"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 };
}
typescript
"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

环境变量

typescript
// 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;
typescript
// 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
    safeParse
    over
    parse
    to avoid scattered
    try/catch
    blocks and leverage TypeScript's control flow narrowing for robust error handling.
  • Do: Use
    z.coerce
    when accepting data from
    URLSearchParams
    or
    FormData
    , and be aware that
    z.coerce.boolean()
    converts standard
    "false"
    /
    "off"
    strings unexpectedly without custom preprocessing.
  • Do: Use
    .flatten()
    or
    .format()
    on
    ZodError
    objects 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
    path
    option in
    .refine()
    or
    .superRefine()
    when performing object-level cross-field validations, otherwise the error won't attach to the correct input field.
  • 建议: 将Schema与使用它们的组件或API路由放在一起,以保持关注点分离。
  • 建议: 始终使用
    z.infer<typeof Schema>
    ,而非手动维护重复的TypeScript接口。
  • 建议: 优先使用
    safeParse
    而非
    parse
    ,避免分散的
    try/catch
    块,并利用TypeScript的控制流收窄实现健壮的错误处理。
  • 建议: 当接收
    URLSearchParams
    FormData
    的数据时使用
    z.coerce
    ,注意
    z.coerce.boolean()
    会将标准的"false"/"off"字符串意外转换,需自定义预处理。
  • 建议:
    ZodError
    对象使用
    .flatten()
    .format()
    ,以便轻松提取可序列化、易读的错误信息供前端使用。
  • 避免: 如果创建和更新操作的字段类型或约束不同,不要仅依赖
    .partial()
    作为更新Schema;应定义不同的Schema。
  • 避免: 在执行对象级跨字段验证时,不要忘记在
    .refine()
    .superRefine()
    中传递
    path
    选项,否则错误不会附加到正确的输入字段。

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()
.
问题:
Type instantiation is excessively deep and possibly infinite.
解决方案: 此问题出现在极端的Schema递归(如深度嵌套的自引用Schema)时。对递归结构使用
z.lazy(() => NodeSchema)
,并显式定义基础TypeScript类型,而非仅依赖推断。
问题: 空字符串在使用
.optional()
时通过了验证。 解决方案:
.optional()
允许
undefined
,但不允许空字符串。如果空字符串表示“无值”,使用
.or(z.literal(""))
或预处理:
z.string().transform(v => v === "" ? undefined : v).optional()