forms
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Form Patterns
React表单模式
Standard stack: React Hook Form + Zod. Keep schema and UI behavior aligned.
标准技术栈:React Hook Form + Zod。保持校验规则与UI行为一致。
Use This Skill When
适用场景
- Building new forms with validation.
- Refactoring unstable form state logic.
- Implementing multi-step, dynamic, or async-validated forms.
- 构建带验证的新表单。
- 重构不稳定的表单状态逻辑。
- 实现多步骤、动态或异步验证的表单。
Core Contract
核心准则
- Keep schema as source of truth (Zod).
- Use typed form values inferred from schema.
- Validate at client and server boundaries.
- Separate field rendering from submit side effects.
- Keep form loading/error states explicit.
- 以Zod校验规则作为唯一可信源。
- 使用从校验规则中推导的TypeScript类型化表单值。
- 在客户端和服务端边界均进行验证。
- 将字段渲染与提交副作用分离。
- 明确处理表单加载/错误状态。
Implementation Workflow
实现流程
1) Baseline Form
1) 基础表单
- Create Zod schema.
- Infer TypeScript type from schema.
- Initialize RHF with resolver and defaults.
- Render errors at field-level and form-level.
- 创建Zod校验规则。
- 从校验规则推导TypeScript类型。
- 使用解析器和默认值初始化RHF(React Hook Form)。
- 在字段级和表单级渲染错误信息。
2) Advanced Patterns
2) 进阶模式
- Multi-step:
- separate per-step schema
- aggregate typed payload
- explicit next/back transitions
- Dynamic arrays:
- use
useFieldArray - stable keys and predictable remove/append behavior
- Async validation:
- debounce expensive validators
- isolate network errors from sync schema errors
- File upload:
- validate type/size before submit
- keep upload state and retry logic explicit
- 多步骤表单:
- 为每个步骤单独设置校验规则
- 聚合类型化的表单数据
- 明确的下一步/上一步切换逻辑
- 动态数组:
- 使用钩子
useFieldArray - 确保键的稳定性以及可预测的删除/追加行为
- 使用
- 异步验证:
- 对耗时的验证器进行防抖处理
- 将网络错误与同步校验规则错误区分开
- 文件上传:
- 提交前验证文件类型/大小
- 明确处理上传状态和重试逻辑
3) Server Integration
3) 服务端集成
- Normalize server errors to RHF-compatible shape.
- Keep optimistic UI optional and reversible.
- For server actions, preserve idempotent submit behavior.
- 将服务端错误转换为RHF兼容的格式。
- 可选实现可逆的乐观UI。
- 对于服务端操作,保持提交的幂等性。
UX and Accessibility Checklist
用户体验与无障碍检查清单
- Keyboard navigation works for all inputs.
- Error messages are specific and linked to fields.
- Submit button state reflects in-flight operations.
- Success and failure feedback is visible and deterministic.
- 所有输入框支持键盘导航。
- 错误信息具体且关联到对应字段。
- 提交按钮状态反映当前操作进度。
- 成功与失败反馈清晰且可预测。
Output Requirements for Agent
Agent输出要求
- Schema design.
- Form state model.
- Validation and submission flow.
- Error handling and accessibility checks.
- 校验规则设计。
- 表单状态模型。
- 验证与提交流程。
- 错误处理与无障碍检查。
References
参考资料
- Detailed code templates (basic, shadcn, multi-step, arrays, uploads):
references/guide.md
- 详细代码模板(基础版、shadcn版、多步骤版、数组版、上传版):
references/guide.md