Chuyển đến nội dung
Skillpedia
Lập trình chung48k · #6241

zod-validation-expert

Skill này làm gì

Chuyên gia này giúp tạo các quy tắc để kiểm tra dữ liệu trong chương trình của bạn. Nó đảm bảo thông tin đi vào hệ thống là đúng và đúng định dạng, bằng công cụ có tên Zod.

Khi nào nên dùng

  • ✓Khi tạo biểu mẫu cho website.
  • ✓Khi nhận dữ liệu từ các nguồn khác (như API).
  • ✓Khi thiết lập biến môi trường trong dự án.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/zod-validation-expert/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/zod-validation-expert/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Tạo một quy tắc để kiểm tra email và mật khẩu có ít nhất 8 ký tự.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Bạn xác định kiểu dữ liệu mong đợi (văn bản, số, v.v.) và các quy tắc (độ dài tối thiểu, định dạng cụ thể). Zod dùng các quy tắc này để kiểm tra xem dữ liệu nhận được có đúng không.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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

…

Câu hỏi thường gặp

Zod là gì?

Zod là công cụ giúp đảm bảo dữ liệu trong mã của bạn đúng, ngăn ngừa lỗi. Nó tạo ra một “khuôn” cho dữ liệu và kiểm tra xem mọi thứ có khớp không.

Tại sao dùng Zod thay vì chỉ dùng TypeScript?

TypeScript kiểm tra kiểu dữ liệu trong lúc phát triển (khi bạn đang viết mã). Zod kiểm tra kiểu dữ liệu lúc chạy (khi chương trình đang hoạt động và nhận dữ liệu), điều này rất cần thiết với dữ liệu từ bên ngoài.

“Infer type” nghĩa là gì?

Nghĩa là Zod có thể tự động tạo định nghĩa kiểu TypeScript từ các quy tắc bạn đã đặt, giúp bạn tiết kiệm công sức và tránh sai lệch.

Chi tiết

Mô tả gốc của tác giả

Expert in Zod — TypeScript-first schema validation. Covers parsing, custom errors, refinements, type inference, and integration with React Hook Form, Next.js, and tRPC.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#6241
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự