Examples
Validation and recovery
A failed submit summarizes errors, moves focus to the summary, and links each message to its field.
Teammate invitation form with validation summary and recovery links
"use client";
import { useEffect, useId, useRef, useState } from "react";
import type { FormEvent, MouseEvent } from "react";
import { CheckCircleIcon } from "@phuctech/ui/icons";
import { Button } from "@phuctech/ui/components/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@phuctech/ui/components/card";
import { Field, FieldDescription, FieldError, FieldLabel } from "@phuctech/ui/components/field";
import { Input } from "@phuctech/ui/components/input";
type FormValues = {
name: string;
email: string;
role: string;
};
type FormField = keyof FormValues;
type FormErrors = Partial<Record<FormField, string>>;
const fieldOrder: readonly FormField[] = ["name", "email", "role"];
const fieldLabels: Record<FormField, string> = {
name: "Name",
email: "Email",
role: "Role",
};
const initialValues: FormValues = {
name: "",
email: "",
role: "",
};
function validateField(field: FormField, value: string) {
if (field === "name" && !value.trim()) {
return "Enter the teammate’s name before reviewing the invitation.";
}
if (field === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim())) {
return "Enter a valid email address, such as name@example.com.";
}
if (field === "role" && !value.trim()) {
return "Add a brief role so the invitation explains why this person is joining.";
}
return undefined;
}
function validate(values: FormValues): FormErrors {
return Object.fromEntries(
fieldOrder.flatMap((field) => {
const error = validateField(field, values[field]);
return error ? [[field, error]] : [];
}),
) as FormErrors;
}
export function FormsPattern() {
const [values, setValues] = useState<FormValues>(initialValues);
const [errors, setErrors] = useState<FormErrors>({});
const [invalidSubmitCount, setInvalidSubmitCount] = useState(0);
const [submitted, setSubmitted] = useState(false);
const [saving, setSaving] = useState(false);
const idPrefix = `invite-${useId().replace(/:/g, "")}`;
const errorSummaryRef = useRef<HTMLDivElement>(null);
const reviewTimerRef = useRef<number | null>(null);
const fieldIds: Record<FormField, string> = {
name: `${idPrefix}-name`,
email: `${idPrefix}-email`,
role: `${idPrefix}-role`,
};
const errorIds: Record<FormField, string> = {
name: `${idPrefix}-name-error`,
email: `${idPrefix}-email-error`,
role: `${idPrefix}-role-error`,
};
const roleHelpId = `${idPrefix}-role-help`;
const formTitleId = `${idPrefix}-title`;
const summaryTitleId = `${idPrefix}-error-summary-title`;
const errorFields = fieldOrder.filter((field) => errors[field]);
const errorSummaryTitle = errorFields.length === 1
? "Review this field"
: `Review these ${errorFields.length} fields`;
useEffect(() => {
if (invalidSubmitCount > 0) {
errorSummaryRef.current?.focus();
}
}, [invalidSubmitCount]);
useEffect(() => () => {
if (reviewTimerRef.current !== null) {
window.clearTimeout(reviewTimerRef.current);
}
}, []);
function clearReviewTimer() {
if (reviewTimerRef.current !== null) {
window.clearTimeout(reviewTimerRef.current);
reviewTimerRef.current = null;
}
}
function updateValue(field: FormField, value: string) {
setValues((current) => ({ ...current, [field]: value }));
setErrors((current) => {
if (!current[field]) return current;
const nextErrors = { ...current };
const nextError = validateField(field, value);
if (nextError) {
nextErrors[field] = nextError;
} else {
delete nextErrors[field];
}
return nextErrors;
});
setSubmitted(false);
}
function handleErrorLinkClick(event: MouseEvent<HTMLAnchorElement>, field: FormField) {
event.preventDefault();
const target = document.getElementById(fieldIds[field]);
target?.focus({ preventScroll: true });
target?.scrollIntoView?.({ block: "center", inline: "nearest" });
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (saving) return;
const nextErrors = validate(values);
setErrors(nextErrors);
setSubmitted(false);
if (Object.keys(nextErrors).length > 0) {
setInvalidSubmitCount((count) => count + 1);
return;
}
clearReviewTimer();
setSaving(true);
reviewTimerRef.current = window.setTimeout(() => {
reviewTimerRef.current = null;
setSaving(false);
setSubmitted(true);
}, 450);
}
function handleCancel() {
clearReviewTimer();
setValues({ ...initialValues });
setErrors({});
setSaving(false);
setSubmitted(false);
}
return (
<Card className="w-full max-w-2xl">
<form onSubmit={handleSubmit} noValidate aria-labelledby={formTitleId}>
<CardHeader>
<CardTitle id={formTitleId}>Invite a teammate</CardTitle>
<CardDescription>
Collect the minimum context before reviewing an invitation.
</CardDescription>
</CardHeader>
<CardContent className="grid gap-6">
{errorFields.length > 0 ? (
<div
ref={errorSummaryRef}
className="grid gap-2 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-foreground focus-ring"
role="group"
aria-labelledby={summaryTitleId}
tabIndex={-1}
>
<h4 id={summaryTitleId} className="font-semibold">{errorSummaryTitle}</h4>
<ul className="grid gap-2 pl-5">
{errorFields.map((field) => (
<li key={field} className="min-w-0 list-disc break-words">
<a
className="break-words underline underline-offset-2 decoration-border hover:decoration-current focus-ring"
href={`#${fieldIds[field]}`}
onClick={(event) => handleErrorLinkClick(event, field)}
>
<span className="font-medium">{fieldLabels[field]}:</span> {errors[field]}
</a>
</li>
))}
</ul>
</div>
) : null}
<div className="grid gap-3">
<div>
<h4 className="text-sm font-semibold text-foreground">Contact details</h4>
<p className="mt-1 text-sm text-muted-foreground">
Use a name and email the teammate will recognize.
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<Field invalid={Boolean(errors.name)}>
<FieldLabel htmlFor={fieldIds.name}>Name</FieldLabel>
<Input
id={fieldIds.name}
name="name"
autoComplete="name"
value={values.name}
onChange={(event) => updateValue("name", event.target.value)}
aria-invalid={Boolean(errors.name) || undefined}
aria-describedby={errors.name ? errorIds.name : undefined}
required
disabled={saving}
/>
<FieldError id={errorIds.name} match={Boolean(errors.name)} aria-live="off">
{errors.name}
</FieldError>
</Field>
<Field invalid={Boolean(errors.email)}>
<FieldLabel htmlFor={fieldIds.email}>Email</FieldLabel>
<Input
id={fieldIds.email}
name="email"
type="email"
autoComplete="email"
value={values.email}
onChange={(event) => updateValue("email", event.target.value)}
aria-invalid={Boolean(errors.email) || undefined}
aria-describedby={errors.email ? errorIds.email : undefined}
required
disabled={saving}
/>
<FieldError id={errorIds.email} match={Boolean(errors.email)} aria-live="off">
{errors.email}
</FieldError>
</Field>
</div>
</div>
<div className="grid gap-3 border-t border-border pt-5">
<div>
<h4 className="text-sm font-semibold text-foreground">Role and access</h4>
<p className="mt-1 text-sm text-muted-foreground">
Explain why this person is joining before choosing permissions.
</p>
</div>
<Field invalid={Boolean(errors.role)}>
<FieldLabel htmlFor={fieldIds.role}>Role</FieldLabel>
<Input
id={fieldIds.role}
name="role"
autoComplete="organization-title"
placeholder="Product designer"
value={values.role}
onChange={(event) => updateValue("role", event.target.value)}
aria-invalid={Boolean(errors.role) || undefined}
aria-describedby={errors.role ? `${roleHelpId} ${errorIds.role}` : roleHelpId}
required
disabled={saving}
/>
<FieldDescription id={roleHelpId}>
Keep this short; it appears in the invitation.
</FieldDescription>
<FieldError id={errorIds.role} match={Boolean(errors.role)} aria-live="off">
{errors.role}
</FieldError>
</Field>
</div>
{submitted ? (
<p className="flex min-w-0 items-center gap-2 break-words text-sm text-[color:var(--color-success-text)]" role="status">
<CheckCircleIcon aria-hidden="true" className="size-4 shrink-0" />
Review complete. No invitation was sent in this example.
</p>
) : null}
</CardContent>
<CardFooter className="flex-wrap">
<Button type="submit" loading={saving} loadingLabel="Reviewing invitation">
Review invitation
</Button>
<Button type="button" variant="outline" onClick={handleCancel}>
Cancel
</Button>
</CardFooter>
</form>
</Card>
);
}
When to use
Use this pattern for a form that collects related information and ends with an explicit review, save, or submit action. Keep domain rules in the screen or feature; the pattern only gives those rules a predictable structure.
Layout
- Group fields by the decision the person is making, then separate groups with a quiet divider.
- Use one visible label per control. Use a two-column row only when the fields remain easy to scan at the smallest supported width.
- Keep the action row together at the end. The primary action says what will happen next; the secondary action cancels or returns without saving.
- For a long form, keep the page or form body scrollable and leave the action row in a stable place. Do not hide the only submit action behind a clipped region.
Validation and recovery
Validate on submit when that is the least noisy moment that still helps the task. Show each error beside its field and repeat the current errors in a summary before the fields. After every invalid submit, move focus to the summary, including when the same errors remain. Each summary link focuses its matching field. Once an error appears, revalidate only that field as its value changes; keep errors in other fields and preserve the other entered values.
While the example reviews valid values, its fields are disabled and the Cancel action stops the simulated delay. Unmounting also clears that timer. The success status says the review is complete and explicitly states that no invitation was sent. The preview and Code/Copy tabs use the same source file, src/components/design/examples/source/forms-pattern.tsx; the file contains fixture behavior and makes no backend request. This pattern has no property playground because it has no public pattern-level props to explore.
Accessibility
- Connect each
FieldLabelto its control withhtmlForand a unique ID. Keep the field description inaria-describedbyand include an error ID only while that error exists. - The summary is a named, focusable group. Focusing it announces the available errors; inline errors do not make a second live announcement, and remain available through the field’s description relationship.
- Use
aria-invalidonly for an invalid value and mark genuinely required fields withrequired. - Announce completion with a
role="status"message that describes the example’s actual action. - Test the full path with a keyboard: submit with errors, move through the error links, correct fields, and submit again.
Do and don’t
Keep errors specific, linked to the fields they describe, and visible until the field value is valid or the form is reset.
Put fetch calls or business validation inside Field, rely on a placeholder as the only label, or claim a simulated review sent data.