Form validation
The house pattern for validating a form: when to validate, where the message goes, and how the error summary behaves.
Purpose
This is a pattern, not a component — a composition of Field, Input, Select and Alert that answers the three questions every form raises: when to validate, where each message goes, and where focus lands when a submit fails. Follow it and every form in the product fails the same way.
The four rules
- Validate on submit — plus on blur for expensive checks. Never while the user is still typing a field for the first time.
- Inline errors via
Field—errorreplaces the hint, and a direct control child is wired automatically:aria-invalid(which drives the error styling) plusaria-describedbypointing at the message. Composed controls (a Select, a wrapped input) are wired by hand on the control itself, using the derived{id}-errorid. - Error summary on top — after a failed submit, a destructive
Alertlists every error and receives focus, so keyboard and screen-reader users get one landing place. Each entry links to its field. - Errors clear as they are fixed — re-validate a field on change once it has been marked invalid.
Example
Submit the form empty to see all four rules fire at once.
Inline errors via Field
Hold errors in one keyed record; each row reads its own entry. A single element child is
all the wiring Field needs — while error is set it clones the child with
aria-invalid (which triggers the input's error styling) and aria-describedby
pointing at the {htmlFor}-error message, so the error is announced with the input.
const [errors, setErrors] = React.useState<Record<string, string>>({});
<Field label="Member email" htmlFor="email" required error={errors.email}>
<Input id="email" type="email" value={values.email} onChange={onChange} />
</Field>
// While errors.email is set, the Input renders with:
// aria-invalid → error border, no extra className needed
// aria-describedby="email-error" → the message is read with the inputComposed controls
Field can only wire a single element child. A Radix Select's root renders no DOM,
so Field cannot reach the trigger through it — put the attributes on the trigger
yourself, using the derived {id}-error id. Same story for any wrapped input.
<Field label="Benefit type" htmlFor="benefit" required error={errors.benefit}>
<Select value={values.benefit || undefined} onValueChange={setBenefit}>
<SelectTrigger
id="benefit"
aria-invalid={!!errors.benefit}
aria-describedby={errors.benefit ? "benefit-error" : undefined}
className={errors.benefit ? "border-destructive" : undefined}
>
<SelectValue placeholder="Select a benefit type" />
</SelectTrigger>
<SelectContent>…</SelectContent>
</Select>
</Field>The error summary
On a failed submit, render a destructive Alert above the fields and move focus to it.
It is focusable once (tabIndex={-1}), never in the Tab order; each entry is a link to
its field's id, so the fix is one keypress away.
const summaryRef = React.useRef<HTMLDivElement>(null);
const onSubmit = (ev: React.FormEvent) => {
ev.preventDefault();
const e = validate(values);
setErrors(e);
if (Object.keys(e).length > 0) {
requestAnimationFrame(() => summaryRef.current?.focus());
}
};
{Object.keys(errors).length > 0 && (
<Alert variant="destructive" role="alert" tabIndex={-1} ref={summaryRef}>
<AlertTitle>Fix the following to continue</AlertTitle>
<AlertDescription>
<ul>
{Object.entries(errors).map(([id, msg]) => (
<li key={id}>
<a href={"#" + id}>{msg}</a>
</li>
))}
</ul>
</AlertDescription>
</Alert>
)}Errors clear as they are fixed
Once a field has been flagged, re-validate it on every change — the message disappears the moment the value is right, and the summary shrinks with it. Fields that have never failed stay untouched, which is what keeps rule 1 honest.
const set = (key: keyof typeof values) => (val: string) => {
const next = { ...values, [key]: val };
setValues(next);
if (errors[key]) setErrors(validate(next)); // only once flagged
};Structure
The anatomy of the pattern, top to bottom — one <form noValidate> owning it all
(noValidate because the pattern replaces the browser's bubbles, not adds to them).
| Part | What it is |
|---|---|
| Error summary | Destructive Alert at the top of the form; rendered only after a failed submit; receives focus |
| Field rows | One Field per control — label, control, hint or error; vertical stack |
| Submit row | The submit Button last, after every field |
Best practices
Do
- Validate on submit; add blur validation only for checks worth interrupting for.
- Write errors as what to do next — "Enter a valid email address", not "Invalid input".
- Keep the summary's entries in the form's visual order, one link per error.
- Show the success
Alertin the same slot the summary occupied — the page's one status position. - Use
noValidateon the form so the browser's native bubbles do not compete with the pattern.
Don't
- Flag a field while the user is still typing in it for the first time.
- Rely on the red border alone — every error carries a written message via
Field. - Leave stale errors standing after the user has fixed the value.
- Move focus to the first invalid field instead of the summary — with several errors, the summary is the map.
- Disable the submit button until the form is valid — it hides the pattern instead of teaching it.
Accessibility & keyboard
- The summary is
role="alert"(assertive live region) withtabIndex={-1}and receives programmatic focus after a failed submit — screen readers announce it immediately and keyboard users land on it. - Each summary entry is an anchor to its field's
id, so every error is reachable in one activation. - Per field,
Fieldsetsaria-invalidon the control andaria-describedbypointing at the{htmlFor}-errormessage — the error is read as part of the field, not found later. Composed controls carry the same attributes by hand. - Errors are never colour-only: the border change always pairs with a written message.
- Keyboard: Tab moves through fields in order; Enter submits; after a failed submit, focus is on the summary and Tab reaches its links.
Props
A pattern has no props of its own — the API is the sum of its parts:
FieldProps carries the label, hint and error;
AlertProps carries the summary's variant. The canonical
implementation lives in
Storybook → Patterns → Form Validation.