跳到正文
cccskills
免费在 GitHub 公开

zod-form-validation

Zod schema validation and React Hook Form integration for TypeScript frontends. This skill should be used when creating forms, defining API schemas, validating form data, implementing type-safe validation, using ZodResolver with React Hook Form, or migrating legacy forms to the Zod + React Hook Form pattern.

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(4)

  • SKILL.md4.0 KB
  • references/form-fields.md8.1 KB
  • references/react-hook-form.md6.0 KB
  • references/zod-schemas.md4.9 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Zod Form Validation Skill

Implements type-safe form validation using Zod schemas with React Hook Form integration in the DTX frontend.

Quick Reference

Form Setup Pattern

import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from '~/components/ui/form';

// 1. Define schema
const MySchema = z.object({
  email: z.string().email('Invalid email'),
  name: z.string().min(2, 'Name too short'),
});

// 2. Create form with zodResolver
const form = useForm<z.infer<typeof MySchema>>({
  resolver: zodResolver(MySchema),
  defaultValues: { email: '', name: '' },
});

// 3. Handle submission
const onSubmit = (data: z.infer<typeof MySchema>) => {
  toast.promise(apiCall(data), {
    loading: 'Saving...',
    success: 'Saved!',
    error: (err) => `Failed: ${err?.response?.data ?? String(err)}`,
  });
};

Form Field Pattern

<FormField
  control={form.control}
  name="email"
  render={({ field }) => (
    <FormItem>
      <FormLabel>Email</FormLabel>
      <FormControl>
        <Input {...field} />
      </FormControl>
      <FormMessage />
    </FormItem>
  )}
/>

Project Conventions

Schema Location

Define schemas in ~/components/<feature>/schemas.ts:

  • UserSchema in ~/components/user/schemas.ts
  • TeamSchema in ~/components/team/schemas.ts
  • GameSchema in ~/components/game/schemas.ts

Type Extraction

Always use z.infer<typeof Schema> for types instead of manual interfaces:

export const UserSchema = z.object({ /* ... */ });
export type UserType = z.infer<typeof UserSchema>;

Error Handling

Wrap mutations in toast.promise():

import { toast } from 'sonner';
import { getLogger } from '~/lib/logger';

const log = getLogger('FormComponent');

toast.promise(apiCall(data), {
  loading: 'Processing...',
  success: (response) => {
    setData(response);
    return 'Success!';
  },
  error: (err) => {
    log.error('API call failed', err);
    return `Failed: ${err?.response?.data ?? String(err)}`;
  },
});

Detailed References

For comprehensive documentation:

Migration Guide

When migrating legacy forms from manual useState to React Hook Form + Zod:

  1. Create/update schema in schemas.ts
  2. Replace useState with useForm({ resolver: zodResolver(Schema) })
  3. Replace input handlers with <FormField> components
  4. Remove manual error state management
  5. Wrap form in <Form {...form}> provider

Reference implementation: ~/pages/profile/profile.tsx

Common Patterns

Nested Objects

const Schema = z.object({
  user: z.object({
    name: z.string(),
    email: z.string().email(),
  }),
});

<FormField control={form.control} name="user.name" ... />

Optional & Nullable

const Schema = z.object({
  nickname: z.string().nullable().optional(),
  mmr: z.number().min(0).nullable().optional(),
});

Select Fields (Number Values)

<FormField
  control={form.control}
  name="position"
  render={({ field }) => (
    <Select onValueChange={(v) => field.onChange(Number(v))} defaultValue={field.value?.toString()}>
      {/* options */}
    </Select>
  )}
/>

Dependencies

Required packages (already installed in DTX frontend):

  • zod: ^4.1.5
  • react-hook-form: ^7.62.0
  • @hookform/resolvers: ^5.2.1

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

aesthetic

免费

Create aesthetically beautiful interfaces following proven design principles. Use when building UI/UX, analyzing designs from inspiration sites, generating design images with ai-multimodal, implementing visual hierarchy and color theory, adding micro-interactions, or creating design documentation. Includes workflows for capturing and analyzing inspiration screenshots with chrome-devtools and ai-multimodal, iterative design image generation until aesthetic standards are met, and comprehensive design system guidance covering BEAUTIFUL (aesthetic principles), RIGHT (functionality/accessibility), SATISFYING (micro-interactions), and PEAK (storytelling) stages. Integrates with chrome-devtools, ai-multimodal, media-processing, ui-styling, and web-frameworks skills.

中文简介正在准备中。当前显示原文说明。

kettleofketchup/DraftForge152026年10月19日 更新

Proper usage of Bash and file operation tools. Use this skill when executing shell commands, writing files, or when tempted to use echo/cat/heredoc to pipe content to files. Prevents permission circumvention patterns like piping multiline content through echo instead of using Write tool. Covers Bash tool, Write tool, Edit tool, and Read tool best practices.

中文简介正在准备中。当前显示原文说明。

kettleofketchup/DraftForge152026年10月19日 更新

brand

免费

DraftForge brand/theming review. Flags raw <button> over PrimaryButton/SecondaryButton, hardcoded violet/slate over brand tokens, inline styles, missing UserAvatar/EntityBreadcrumb.

中文简介正在准备中。当前显示原文说明。

kettleofketchup/DraftForge152026年10月19日 更新

Browser automation, debugging, and performance analysis using Puppeteer CLI scripts. Use for automating browsers, taking screenshots, analyzing performance, monitoring network traffic, web scraping, form automation, and JavaScript debugging.

中文简介正在准备中。当前显示原文说明。

kettleofketchup/DraftForge152026年10月19日 更新

Django Redis caching with django-cacheops. This skill should be used when implementing caching, adding cache invalidation, optimizing API performance, modifying models that affect cached data, or debugging cache-related issues in the Django backend.

中文简介正在准备中。当前显示原文说明。

kettleofketchup/DraftForge152026年10月19日 更新

Frontend development guidelines for React/TypeScript applications. Modern patterns including Suspense, lazy loading, useSuspenseQuery, file organization with features directory, MUI v7 styling, TanStack Router, performance optimization, and TypeScript best practices. Use when creating components, pages, features, fetching data, styling, routing, or working with frontend code.

中文简介正在准备中。当前显示原文说明。

kettleofketchup/DraftForge152026年10月19日 更新

查看 kettleofketchup 的全部技能

报告此技能的问题