Token导航 LogoToken导航TokenDH.com
前端设计敏感数据github未标认证来源可访问许可证需确认审计通过

zod-validation-expertZod 验证专家

Agent Skill

zod-validation-expert 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,830

周安装

77

GitHub Stars

35,879

下载量

641
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:zod-validation-expert(Zod 验证专家)
来源仓库:https://github.com/sickn33/antigravity-awesome-skills
仓库路径:skills/zod-validation-expert
安装命令:
npx skills add https://github.com/sickn33/antigravity-awesome-skills --skill zod-validation-expert
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/sickn33/antigravity-awesome-skills --skill zod-validation-expert

简介

zod-validation-expert 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态、代码变更或协作事项进行整理。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装并使用。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

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

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().

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.68%
按下载量换算229

Claude

27.55%
按下载量换算177

Cursor

19.21%
按下载量换算123

Gemini CLI

8.92%
按下载量换算57

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills