zod

HuynhSang2005's avatarfrom HuynhSang2005

Quy ước dùng Zod trong repo (schemas folder, Vietnamese messages, integration với react-hook-form và server actions).

⭐0stars🔀0forks📁View on GitHub🕐Updated Jan 10, 2026

When & Why to Use This Skill

This Claude skill provides a comprehensive framework and set of conventions for implementing Zod schema validation within a TypeScript repository. It focuses on standardizing schema organization, implementing Vietnamese localization for validation messages, and ensuring seamless integration with React Hook Form and Server Actions to maintain high type safety and code consistency.

Use Cases

  • Centralizing data validation logic by organizing Zod schemas within a dedicated directory to ensure a single source of truth across the codebase.
  • Implementing localized Vietnamese error messages for form validation to improve user experience while maintaining technical precision.
  • Integrating Zod with react-hook-form and server actions to achieve end-to-end type safety from the UI layer to the backend handlers.
  • Enforcing modern Zod v4 best practices and strict TypeScript patterns to prevent the use of unsafe types like 'any' and reduce technical debt.
namezod
descriptionQuy ước dùng Zod trong repo (schemas folder, Vietnamese messages, integration với react-hook-form và server actions).

Nguồn trong repo

  • Schemas: apps/web/src/schemas/*.ts
    • Ví dụ: apps/web/src/schemas/blog.ts
  • Resolver: @hookform/resolvers/zod (đã dùng trong admin forms).

Quy ước

  • Định nghĩa schema ở apps/web/src/schemas/<domain>.ts.
  • Xuất type bằng z.infer<typeof schema> để không bị drift.
  • Message validation phải tiếng Việt (giữ thuật ngữ kỹ thuật English khi cần).

Pattern hay dùng (CẬP NHẬT ZOD V4)

  • Optional + nullable (match DB):
    • z.string().max(160).optional().nullable()
  • UUID:
    • z.string().uuid()
  • Enum status:
    • z.enum(['draft', 'published', 'archived'], { error: 'Trạng thái không hợp lệ' })
  • Zod v4: Dùng error: thay vì message: cho custom errors:
    // Zod 4 pattern (KHUYẾN NGHỊ)
    z.string().min(5, { error: "Quá ngắn, tối thiểu 5 ký tự" })
    
    // Zod 3 pattern (vẫn hoạt động nhưng không khuyến nghị)
    z.string().min(5, { message: "Quá ngắn" })
    

Với react-hook-form

  • resolver: zodResolver(schema)
  • Prefer useForm<FormData, unknown, FormData> để types khớp.

Với server actions / route handlers

  • Validate input bằng schema.safeParse(data).
  • Không throw raw ZodError ra UI; map sang message tiếng Việt hoặc cấu trúc lỗi form.

Tránh

  • Tránh z.any() (repo strict TS). Nếu cần, dùng z.unknown() và refine.
  • Tránh duplicate rule giữa client & server; schema nên dùng chung.