build-form-validation
Skill9 starsChanged 5 months agoApache-2.0View on GitHub
Implements type-safe forms with React Hook Form + Zod (or server-action validation) — schemas, field arrays, multi-step flows, and accessible error handling; used when building or fixing forms.
In this repository147 other files it gives its agents.
- second-brain/AGENTS.mdAGENTS.md
- second-brain/CLAUDE.mdCLAUDE.md
- agent-tool-mcp-builderSkill
- api-design-reviewSkill
- async-concurrency-correctnessSkill
- audit-accessibility-wcagSkill
- audit-license-complianceSkill
- audit-technical-seoSkill
- auth-jwt-sessionSkill
- author-codemodSkill
- brainstorm-designSkill
- build-audit-loggingSkill
- build-cdc-streaming-pipelineSkill
- build-cli-toolSkill
- build-data-tableSkill
- build-etl-pipelineSkill
- build-native-mobile-uiSkill
- build-office-docsSkill
- build-offline-first-syncSkill
- build-react-componentSkill
- build-realtime-channelSkill
- build-spreadsheetSkill
- build-vector-searchSkill
- caching-strategySkill
- cicd-pipeline-authorSkill
- cloud-cost-optimizeSkill
- code-commentsSkill
- code-reviewSkill
- compose-local-dev-stackSkill
- configure-bundler-buildSkill
- configure-dns-tlsSkill
- configure-reverse-proxy-lbSkill
- configure-security-headers-cspSkill
- contract-testingSkill
- datetime-timezone-correctnessSkill
- db-migration-safetySkill
- debug-ci-pipeline-failureSkill
- debug-flaky-testsSkill
- debug-frontend-browserSkill
- debug-root-causeSkill
- defend-llm-prompt-injectionSkill
- deliver-webhooksSkill
- dependency-upgradeSkill
- deploy-releaseSkill
- design-api-paginationSkill
- design-authorization-modelSkill
- design-backup-dr-recoverySkill
- design-event-sourcing-cqrsSkill
- design-multi-tenancySkill
- design-protobuf-grpc-serviceSkill
- design-relational-schemaSkill
- design-search-index-infraSkill
- design-state-machineSkill
- design-token-systemSkill
- diff-table-paritySkill
- distributed-locks-leasesSkill
- dockerfile-optimizeSkill
- encrypt-sensitive-dataSkill
- error-messageSkill
- estimate-workSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
10 rules. About 0 are common, 3 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 9
Use this skill when building or fixing a form in a React/Next.js codebase — anything touching react-hook-form, zod, zodResolver, field …
- Distinctive: line 11
Not this skill: pure REST/RPC contract or response-shape review (that is API design review).
- Very specific: line 15
Check installed versions: react-hook-form v7+, zod v3 vs v4 (error API differs), @hookform/resolvers.
- Distinctive: line 16
Look for an existing form in the repo and match its pattern (UI lib, resolver setup, error component) instead of inventing a new one.
- Very specific: line 20
One Zod schema = source of truth: Write the schema once, derive the TS type with z.infer, and import the *same* schema on client and server.
- Very specific: line 35
Wire React Hook Form with the resolver: Use zodResolver, set defaultValues for *every* field (uncontrolled inputs need them or they switch …
- Very specific: line 46
Field arrays + nested objects: use useFieldArray. Key the rows by field.id (RHF's stable id), never by array index — index keys corrupt …
- Very specific: line 52
Read nested errors via form.formState.errors.items?.[index]?.name.
- Distinctive: line 95
Run these before declaring done — show evidence, not just "fixed":
- Very specific: line 103
If a contract or behavior is testable, add/run a unit test on the schema (safeParse of good + bad payloads) so the validation can't …
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
When to Use
Use this skill when building or fixing a form in a React/Next.js codebase — anything touching react-hook-form, zod, zodResolver, field arrays, multi-step/wizard flows, or server-action input validation. This covers the client form layer: schema-driven validation, RHF wiring, accessible errors, and the client↔server-action contract.
Not this skill: pure REST/RPC contract or response-shape review (that is API design review). This skill stops at "the action received validated input and returned a typed result."
First, detect the stack before writing code:
grep -r "next" package.jsonand check for anapp/dir → App Router (server actions +useActionStateavailable on React 19).- Check installed versions:
react-hook-formv7+,zodv3 vs v4 (error API differs),@hookform/resolvers. - Look for an existing form in the repo and match its pattern (UI lib, resolver setup, error component) instead of inventing a new one.
Steps
- One Zod schema = source of truth. Write the schema once, derive the TS type with
z.infer, and import the same schema on client and server. Never hand-write a parallelinterface.
For inputs that arrive as strings but mean numbers/dates, use// schema.ts — shared export const signupSchema = z.object({ email: z.string().email(), password: z.string().min(8), confirm: z.string(), }).refine((d) => d.password === d.confirm, { message: "Passwords must match", path: ["confirm"], // attaches error to the field, not the form root }); export type SignupInput = z.infer<typeof signupSchema>;z.coerce.number()/z.coerce.date()so form values and serverFormDataboth parse. - Wire React Hook Form with the resolver. Use
zodResolver, setdefaultValuesfor every field (uncontrolled inputs need them or they switch controlled→uncontrolled mid-edit), and pick a sanemode.const form = useForm<SignupInput>({ resolver: zodResolver(signupSchema), defaultValues: { email: "", password: "", confirm: "" }, mode: "onTouched", // validate after blur, then re-validate onChange — best UX default });- Native inputs (
<input>,<select>): use{...form.register("email")}. - Custom/headless components (Select, DatePicker, anything not exposing a ref): wrap in
<Controller name=... control={form.control} render={...} />. Mixingregisteron a controlled component silently drops values.
- Native inputs (
- Field arrays + nested objects use
useFieldArray. Key the rows byfield.id(RHF's stable id), never by array index — index keys corrupt state on remove/reorder.
Read nested errors viaconst { fields, append, remove } = useFieldArray({ control: form.control, name: "items" }); // register nested path: {...form.register(`items.${index}.name`)}form.formState.errors.items?.[index]?.name. - Multi-step / wizard: one sub-schema per step; validate only the current step's fields before advancing with
await form.trigger(["fieldA","fieldB"]). Keep all steps in oneuseForminstance (do not remount per step or you lose state). Persist between steps with a singleuseForm+ (optionally)localStorage/URL state; validate the full schema on final submit. Compose withsignupSchema.pick({...})or.partial()per step so the final type stays one source of truth. - Next.js server actions — validate inside the action, return typed errors, do not
throwfor validation:
On the client (React 19):"use server"; export async function signup(_prev: State, formData: FormData): Promise<State> { const parsed = signupSchema.safeParse(Object.fromEntries(formData)); if (!parsed.success) { return { ok: false, errors: parsed.error.flatten().fieldErrors }; } // ...mutate DB... revalidatePath("/dashboard"); // or revalidateTag — refresh cache after mutation return { ok: true }; }const [state, action, pending] = useActionState(signup, { ok: false });. Bind RHF to the action with<form action={action}>andform.handleSubmitfor client-side pre-check, or surfacestate.errorsback into RHF viaform.setError. Always re-validate server-side — client validation is UX, not security. - Accessible errors on every field:
aria-invalid={!!errors.email}on the input.aria-describedby="email-error"pointing at the error node; the error node hasid="email-error"androle="alert"(or sits in anaria-live="polite"region) so SRs announce it.- Associate a real
<label htmlFor>; placeholders are not labels. - On failed submit, focus the first errored field. RHF does this with
shouldFocusError: true(default) for registered native inputs; forController/custom inputs, focus manually in the submit-error handler.
- Async validation (e.g. "username taken"): debounce the check (~300–500ms), and validate server-side too. Either a Zod
.refine(async ...)(requiresparseAsync/safeParseAsync—zodResolverhandles this) orform.setError("username", { message })after a fetch. Disable submit whileformState.isValidating || isSubmittingto prevent races.
Common Errors
defaultValuesmissing → "controlled to uncontrolled" warning and lost values. Always seed every field, including arrays ({ items: [] }).- Field array keyed by index → on
remove(2)the wrong rows re-render / values shift. Key byfield.id. Controllervalue not updating because the inner component fires a non-standard onChange — map it:onChange={(v) => field.onChange(v)}. Don't spreadregisteronto a controlled component.refine/superRefineerror lands on form root, not the field → user sees no inline message. Setpath: ["confirm"].z.coerceforgotten for number/checkbox inputs →FormDatagives"3"/"on", schema expectsnumber/boolean, every submit fails validation silently.- Server action
throwfor invalid input → blows up as an error boundary / 500 instead of inline errors. UsesafeParse+ return. - Forgot
revalidatePath/revalidateTagafter mutation → UI shows stale cached data post-submit even though the DB changed. - Re-mounting
useFormper wizard step wipes earlier answers. One instance, conditionally render steps. - Trusting client validation only — bypassable; the server action must re-
safeParse. - Zod v3 vs v4 mismatch:
.flatten()and the error object shape changed across majors. Check the installed version before copying error-extraction code. mode: "onChange"on a big form → validates on every keystroke, janky + noisy errors before the user finishes typing. PreferonTouched/onBlur.
Verify
Run these before declaring done — show evidence, not just "fixed":
- Type check:
npx tsc --noEmit(or the project's typecheck script) passes — confirmsz.inferand form generics line up. - Lint: project ESLint passes on touched files.
- Happy path: submit valid data → action runs, success state shows, cache revalidates (data refreshes without a hard reload).
- Validation path: submit each invalid field → inline error appears under the right field, submit is blocked, no 500/error boundary.
- A11y spot-check: invalid field has
aria-invalid="true"andaria-describedbyresolving to a visible error node; first errored field receives focus on failed submit. Verify in the DOM/accessibility tree (e.g. devtools snapshot), not by eye alone. - Field array / wizard (if present): add → remove a middle row → values of remaining rows stay correct; advancing a step only validates that step; final submit validates the whole schema.
- If a contract or behavior is testable, add/run a unit test on the schema (
safeParseof good + bad payloads) so the validation can't silently regress.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

