mcpField
F
form-validation-architect

form-validation-architect

github.com/curiositech开发257192 次安装2 天前更新
代码仓库

关于 form-validation-architect

面向 React 开发表单架构的技能指南,适用于处理复杂校验和交互体验的开发者。内容以 react-hook-form 与 Zod 为重点,涵盖类型安全、多步骤流程、异步校验和自动保存。

主要功能

  1. 01react-hook-form 表单模式
  2. 02Zod 模式与类型推断
  3. 03多步骤向导设计
  4. 04动态字段数组处理
  5. 05异步校验与自动保存

适用场景

  1. 01实现带校验的用户注册表单
  2. 02构建多步骤结账流程
  3. 03制作可增删字段的表单
  4. 04为长表单添加自动保存

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/curiositech/some_claude_skills --skill form-validation-architect

安装后在 Claude Code 中输入/form-validation-architect确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

.claude-plugin/
plugin.json
assets/form-templates/
LoginForm.tsx
MultiStepWizard.tsx
RegistrationForm.tsx
references/
accessibility.md
file-upload.md
zod-patterns.md
scripts/
generate_form.ts
validate_schemas.ts

详细介绍

表单验证架构师

擅长构建生产级表单系统,具备客户端验证、类型安全和出色的用户体验。

适用场景

✅ 适用于:

  • 包含多个字段和验证规则的复杂表单
  • 带进度跟踪的多步骤向导
  • 动态字段数组(添加/删除项目)
  • 跨会话持久化表单状态
  • 异步验证(检查用户名是否可用、验证地址)
  • 依赖字段(勾选 A 后启用 B)
  • 带进度和验证的文件上传
  • 自动保存和乐观更新

❌ 不适用于:

  • 简单的联系表单(使用 HTML + 基础 JS 即可)
  • 仅在后端进行验证(在服务器上使用 Joi、Yup)
  • 非 React 框架(使用 Formik 的替代方案)
  • 只读展示(不需要表单)

快速决策树

Does your form:
├── Have >5 fields? → Use react-hook-form
├── Need type safety? → Add Zod schemas
├── Have dynamic fields? → Use field arrays
├── Span multiple steps? → Use wizard pattern
├── Need async validation? → Use resolver + async rules
└── Just email/message? → Use native HTML validation

技术选择(2024+)

React Hook Form(推荐)

RHF 优于 Formik 的原因:

  • 性能:非受控输入 → 减少重新渲染
  • 包体积:8KB,而 Formik 为 30KB
  • 开发体验:更好的 TypeScript 支持
  • 普及度:4 万多个星标,2023 年起成为行业标准

发展时间线:

  • 2015-2019 年:Formik 占据主导地位
  • 2019 年:React Hook Form 发布
  • 2022 年起:RHF 成为标准
  • 2024 年:Formik 进入维护模式
使用 Zod 进行架构验证

Zod 优于 Yup 的原因:

  • TypeScript 优先:从架构推断类型
  • 可组合性:更便于复用架构
  • 错误消息:更易自定义
  • 现代化:持续开发,支持最新功能

发展时间线:

  • 2017-2020 年:Yup 是标准
  • 2020 年:Zod 发布
  • 2023 年起:新项目更倾向使用 Zod

常见反模式

反模式 1:到处使用受控输入

新手想法:“所有表单输入都应该用 useState 控制”

问题:每次按键都会导致重新渲染

错误做法:

// ❌ Re-renders entire component on every keystroke
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
// ... 20 more useState calls

<input value={email} onChange={(e) => setEmail(e.target.value)} />

正确做法:

// ✅ Uncontrolled with react-hook-form (minimal re-renders)
const { register, handleSubmit } = useForm();

<input {...register('email')} />
<input {...register('password')} />
<input {...register('name')} />

重要性:表单字段达到 10 个或更多时,使用受控输入会导致卡顿。


反模式 2:基于字符串的验证

问题:没有类型安全,容易出错

错误做法:

// ❌ String validation, no types
const validate = (values) => {
  if (!values.email.includes('@')) return 'Invalid email';
  if (values.age < 18) return 'Must be 18+';
  // Typo in field name? Runtime error!
};

正确做法:

// ✅ Zod schema with type inference
const schema = z.object({
  email: z.string().email('Invalid email'),
  age: z.number().min(18, 'Must be 18+'),
  username: z.string()
    .min(3, 'Too short')
    .regex(/^[a-z0-9_]+$/, 'Lowercase, numbers, underscores only')
});

type FormData = z.infer<typeof schema>; // Automatic TypeScript type!

发展时间线:

  • 2020 年以前:基于字符串的验证很常见
  • 2020 年起:架构优先验证成为标准
  • 2024 年:预期可从架构推断类型

反模式 3:不管理错误状态

问题:用户交互前就显示错误

错误做法:

// ❌ Shows errors immediately on page load
{errors.email && <span>{errors.email}</span>}

正确做法:

// ✅ Show errors only after field is touched
const { formState: { errors, touchedFields } } = useForm();

{touchedFields.email && errors.email && (
  <span className="error">{errors.email.message}</span>
)}

// Or: Use mode="onBlur" to validate on blur
const form = useForm({
  mode: 'onBlur' // Validate when user leaves field
});

重要性:改善用户体验 → 不会在用户输入前就对其大喊大叫


反模式 4:没有异步验证

问题:无法检查用户名是否可用、验证地址等

正确做法:

// ✅ Async validation with debounce
const schema = z.object({
  username: z.string().refine(
    async (username) => {
      // Debounced API call
      const available = await checkUsernameAvailability(username);
      return available;
    },
    { message: 'Username already taken' }
  )
});

// Or: Custom async validation in RHF
register('username', {
  validate: {
    checkAvailable: async (value) => {
      const response = await fetch(`/api/check-username?q=${value}`);
      return response.ok || 'Username taken';
    }
  }
});

最佳实践:对异步验证进行防抖,避免频繁调用 API


反模式 5:没有加载状态

问题:用户不知道验证正在进行

正确做法:

// ✅ Show loading state during async validation
const { formState: { isValidating, isSubmitting } } = useForm();

<button disabled={isValidating || isSubmitting}>
  {isSubmitting ? 'Submitting...' :
   isValidating ? 'Checking...' :
   'Submit'}
</button>

实现模式

模式 1:使用 Zod 的基础表单
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

// Define schema
const loginSchema = z.object({
  email: z.string().email('Invalid email address'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
  rememberMe: z.boolean().optional()
});

type LoginForm = z.infer<typeof loginSchema>;

function LoginForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting }
  } = useForm<LoginForm>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      rememberMe: false
    }
  });

  const onSubmit = async (data: LoginForm) => {
    await api.login(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <input
          {...register('email')}
          type="email"
          placeholder="Email"
        />
        {errors.email && <span className="error">{errors.email.message}</span>}
      </div>

      <div>
        <input
          {...register('password')}
          type="password"
          placeholder="Password"
        />
        {errors.password && <span className="error">{errors.password.message}</span>}
      </div>

      <div>
        <label>
          <input {...register('rememberMe')} type="checkbox" />
          Remember me
        </label>
      </div>

      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Logging in...' : 'Login'}
      </button>
    </form>
  );
}
模式 2:多步骤向导
const stepSchemas = [
  // Step 1: Personal Info
  z.object({
    firstName: z.string().min(1, 'Required'),
    lastName: z.string().min(1, 'Required'),
    email: z.string().email()
  }),
  // Step 2: Address
  z.object({
    street: z.string().min(1, 'Required'),
    city: z.string().min(1, 'Required'),
    zipCode: z.string().regex(/^\d{5}$/, 'Invalid ZIP')
  }),
  // Step 3: Payment
  z.object({
    cardNumber: z.string().regex(/^\d{16}$/, 'Invalid card'),
    expiry: z.string().regex(/^\d{2}\/\d{2}$/, 'MM/YY format'),
    cvv: z.string().regex(/^\d{3}$/, '3 digits')
  })
];

function MultiStepForm() {
  const [step, setStep] = useState(0);
  const [formData, setFormData] = useState({});

  const form = useForm({
    resolver: zodResolver(stepSchemas[step])
  });

  const nextStep = async () => {
    const isValid = await form.trigger(); // Validate current step

    if (isValid) {
      setFormData({ ...formData, ...form.getValues() });
      setStep(step + 1);
    }
  };

  const prevStep = () => {
    setFormData({ ...formData, ...form.getValues() });
    setStep(step - 1);
  };

  const onSubmit = async (data) => {
    const finalData = { ...formData, ...data };
    await api.submitApplication(finalData);
  };

  return (
    <div>
      <progress value={step + 1} max={stepSchemas.length} />

      <form onSubmit={form.handleSubmit(step === 2 ? onSubmit : nextStep)}>
        {step === 0 && <PersonalInfoStep register={form.register} errors={form.formState.errors} />}
        {step === 1 && <AddressStep register={form.register} errors={form.formState.errors} />}
        {step === 2 && <PaymentStep register={form.register} errors={form.formState.errors} />}

        <div>
          {step > 0 && <button type="button" onClick={prevStep}>Back</button>}
          <button type="submit">
            {step === 2 ? 'Submit' : 'Next'}
          </button>
        </div>
      </form>
    </div>
  );
}
模式 3:动态字段数组
const schema = z.object({
  items: z.array(z.object({
    name: z.string().min(1, 'Required'),
    quantity: z.number().min(1, 'At least 1'),
    price: z.number().min(0, 'Must be positive')
  })).min(1, 'Add at least one item')
});

function OrderForm() {
  const { register, control, handleSubmit, formState: { errors } } = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      items: [{ name: '', quantity: 1, price: 0 }]
    }
  });

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'items'
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((field, index) => (
        <div key={field.id}>
          <input
            {...register(`items.${index}.name`)}
            placeholder="Item name"
          />
          <input
            {...register(`items.${index}.quantity`, { valueAsNumber: true })}
            type="number"
          />
          <input
            {...register(`items.${index}.price`, { valueAsNumber: true })}
            type="number"
            step="0.01"
          />
          <button type="button" onClick={() => remove(index)}>
            Remove
          </button>
        </div>
      ))}

      <button type="button" onClick={() => append({ name: '', quantity: 1, price: 0 })}>
        Add Item
      </button>

      <button type="submit">Submit Order</button>
    </form>
  );
}
模式 4:自动保存(防抖)
import { useDebounce } from 'use-debounce';
import { useEffect } from 'react';

function AutosaveForm() {
  const { watch, register } = useForm();
  const formValues = watch(); // Watch all fields

  // Debounce to avoid saving on every keystroke
  const [debouncedValues] = useDebounce(formValues, 1000);

  useEffect(() => {
    // Save to localStorage or API
    localStorage.setItem('draft', JSON.stringify(debouncedValues));
    // Or: await api.saveDraft(debouncedValues);
  }, [debouncedValues]);

  return (
    <form>
      <input {...register('title')} placeholder="Title" />
      <textarea {...register('content')} placeholder="Content" />
      <small>Autosaved</small>
    </form>
  );
}

表单用户体验最佳实践

1. 在失焦时验证(而不是在更改时)
const form = useForm({
  mode: 'onBlur' // Validate when user leaves field
  // NOT 'onChange' - too aggressive
});
2. 表单无效时禁用提交
<button
  type="submit"
  disabled={!form.formState.isValid || form.formState.isSubmitting}
>
  Submit
</button>
3. 提交时聚焦第一个错误
const onSubmit = async (data) => {
  try {
    await api.submit(data);
  } catch (error) {
    // Focus first error field
    const firstError = Object.keys(errors)[0];
    form.setFocus(firstError);
  }
};
4. 乐观 UI 更新
const onSubmit = async (data) => {
  // Optimistically update UI
  setItems([...items, data]);

  try {
    await api.createItem(data);
  } catch (error) {
    // Rollback on error
    setItems(items);
    toast.error('Failed to save');
  }
};

生产环境检查清单

□ Zod schemas for all forms
□ Type inference used (z.infer<typeof schema>)
□ Validation mode set appropriately (onBlur/onSubmit)
□ Error messages clear and actionable
□ Loading states for async operations
□ Focus management on errors
□ Autosave for long forms
□ Form state persisted (localStorage/session)
□ File upload progress indicators
□ Keyboard navigation tested
□ Accessibility (ARIA labels, error announcements)
□ Mobile-friendly (large touch targets)

适用与不适用场景

场景使用此技能?
带验证的用户注册✅ 是
多步骤结账流程✅ 是
动态表单生成器✅ 是
简单的新闻简报订阅❌ 否 - 使用原生 HTML
仅在后端进行验证❌ 否 - 在服务器上使用 Joi/Yup
非 React 框架❌ 否 - 使用框架专属解决方案

技术对比

功能RHF + ZodFormik + Yup原生 HTML5
性能⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
类型安全⭐⭐⭐⭐⭐⭐⭐⭐❌
包体积8KB30KB0KB
开发体验⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
字段数组⭐⭐⭐⭐⭐⭐⭐⭐⭐❌
异步验证⭐⭐⭐⭐⭐⭐⭐⭐❌

参考资料

  • /references/zod-patterns.md - 高级 Zod 模式
  • /references/accessibility.md - 表单无障碍指南
  • /references/file-upload.md - 带进度跟踪的文件上传

脚本

  • scripts/generate_form.ts - 根据 Zod 模式生成表单
  • scripts/validate_schemas.ts - 检查 Zod 模式中的常见问题

资源

  • assets/form-templates/ - 可直接使用的表单组件

此技能指导内容:表单验证架构 | react-hook-form 模式 | Zod 模式设计 | 多步骤向导 | 字段数组 | 自动保存 | 异步验证

评论

支持 Markdown