Sub topic 15
Making errors accessible
This chapter covers how to expose form errors to assistive technology such as screen readers. It assumes you can build a form with useForm, register, and zodResolver, and that you read field errors from formState.errors. You should also know basic HTML form elements and React hooks.
Why error text alone is not enough
In the earlier chapters, an error appears as a <p> below an input. Sighted users see it. A screen reader user may not, for three reasons:
- The paragraph is inserted after the user pressed submit, and nothing announces it.
- Nothing ties the message to the input. When focus lands on the input, the reader says "Email, edit text" and stays silent about the error.
- If the error is shown only as a red border, color is the only signal. That fails users who cannot perceive color.
The fix is a few HTML attributes plus one focus rule. React Hook Form already gives you the data you need: errors for the message and setFocus or the built-in focus behavior for moving the cursor.
Tie the message to the input
Use two attributes on every input that can fail:
aria-invalidtells assistive technology that the current value is not valid.aria-describedbypoints to theidof the element that explains the problem. Screen readers read that element after the field's label.
Give each message a stable id, derived from the field name.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});
type SignUpValues = z.infer<typeof signUpSchema>;
export function AccessibleSignUpForm() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
defaultValues: { email: "", password: "" },
});
return (
<form onSubmit={handleSubmit((values) => console.log(values))} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
aria-invalid={errors.email ? "true" : "false"}
aria-describedby={errors.email ? "email-error" : undefined}
{...register("email")}
/>
{errors.email && (
<p id="email-error" role="alert">
{errors.email.message}
</p>
)}
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
aria-invalid={errors.password ? "true" : "false"}
aria-describedby={errors.password ? "password-error" : undefined}
{...register("password")}
/>
{errors.password && (
<p id="password-error" role="alert">
{errors.password.message}
</p>
)}
<button type="submit">Create account</button>
</form>
);
}Pointsria-describedby is set only while the error exists. A reference to an id that is not in the DOM does nothing useful, so undefined` keeps the markup clean.
aria-invalidis a string,"true"or"false". React accepts booleans for this attribute too, but strings make the rendered HTML explicit.- The
labelis linked withhtmlForandid. A visible label is the primary accessible name. Do not useplaceholderas a replacement. noValidateon the form turns off the browser's own validation bubbles. Zod now owns the messages, so users get one consistent set of errors.
Announce errors with role="alert"
role="alert" makes a screen reader announce the element as soon as it appears in the DOM. This works well for one or two messages. The related attribute aria-live="polite" waits until the user is idle instead of interrupting.
| Technique | Behavior | Use it for |
|---|---|---|
| `role="alert"` | Interrupts and reads immediately | Errors after submit, or after a field is left in `onBlur` mode |
| `aria-live="polite"` | Reads when the user pauses | Frequent updates such as `onChange` validation |
| `aria-describedby` | Reads when the field gets focus | The link between each field and its message |
The three work together. role="alert" announces the error when it shows up. aria-describedby repeats it when the user returns to the field.
A caution for onChange mode: with role="alert", a message that changes on every keystroke interrupts the user repeatedly. Choose mode: "onBlur" or mode: "onSubmit" (see the validation modes chapter), or switch to aria-live="polite" for those messages.
Manage focus after a failed submit
After the user presses submit and validation fails, focus stays on the button. A keyboard user then has to tab around to find the problem. React Hook Form fixes this by default. When handleSubmit finds errors, it focuses the first field that has one. This is controlled by the shouldFocusError option, which defaults to true.
const form = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
shouldFocusError: true, // default, shown for clarity
});For this to work, the library must be able to reach the input element. That is the case when you spread register("email") onto a native <input>, because the spread includes a ref. It fails silently in two situations:
- You wrap the input in a custom component that does not forward the
ref. In React 19,refis a normal prop. In React 18, useforwardRef. - You use a controlled component through
Controller. There, you must attachfield.refto the focusable element yourself.
If focus does not move on a failed submit, check the ref first.
Focus order for multiple errors follows the order in which the inputs were registered, not the order of keys in the schema. Keep the field order in the DOM the same as the order a user reads the form.
Move focus manually with setFocus
Sometimes you need to move focus yourself. A server error is the usual case, because handleSubmit has already finished by the time the response arrives. Use setFocus from useForm.
const { setError, setFocus } = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
});
const onSubmit = async (values: SignUpValues) => {
const response = await fetch("/api/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (response.status === 409) {
setError("email", {
type: "server",
message: "This email is already registered",
});
setFocus("email");
}
};setError puts the message in errors.email, so the same accessible markup renders it. setFocus moves the cursor to the field, and the screen reader reads the label and the description.
Summarize errors for long forms
On a form with many fields, the first-error focus is not enough context. Add an error summary at the top that lists every problem with a link to each field. Place it in a container with role="alert" or move focus to its heading after a failed submit.
import type { FieldErrors } from "react-hook-form";
type SummaryProps = { errors: FieldErrors<SignUpValues> };
export function ErrorSummary({ errors }: SummaryProps) {
const entries = Object.entries(errors).filter(([, error]) => error?.message);
if (entries.length === 0) return null;
return (
<div role="alert">
<h2>There are {entries.length} problems with your submission</h2>
<ul>
{entries.map(([name, error]) => (
<li key={name}>
<a href={`#${name}`}>{String(error?.message)}</a>
</li>
))}
</ul>
</div>
);
}This works because each input's id matches its field name (email, password). For nested fields such as address.city, the name contains a dot. A dot in a fragment link still works, but you must give the input the same id.
Common mistakes
- Using
role="alert"on a container that is always in the DOM. Announcement happens when content is added, so render the element only while there is an error, or keep the container and change its text. - Removing the visible label and relying on
aria-labelalone. Sighted users lose the label once they have typed. - Writing vague messages such as "Invalid". Say what is wrong and how to fix it: "Enter a valid email".
- Showing errors only with color. Pair color with text, and keep contrast at 4.5:1 or higher.
- Forgetting
type="button"on helper buttons inside the form, such as "Remove" in a field array. Without it, they submit the form.
Exercises
Exercise
A user submits the sign-up form with an empty email. A screen reader announces the error text. When the user later tabs back to the email input, the reader says only "Email, edit text". Which attribute is missing, and what must it reference?
Show answer
aria-describedby is missing. It must reference the id of the error element, for example aria-describedby="email-error", and the paragraph must have id="email-error".
Exercise
After a failed submit, focus stays on the Submit button even though you spread register("name") onto a custom TextField component. What is the most likely cause, and how do you fix it?
Show answer
The custom component does not pass the ref from register to the underlying <input>, so React Hook Form cannot focus it. Forward the ref (a normal prop in React 19, forwardRef in React 18) and attach it to the native input.
Exercise
The server rejects an email with a 409 status after handleSubmit has already run. Which two calls make the error visible and reachable for a keyboard and screen reader user?
Show answer
setError("email", { type: "server", message: "..." }) stores the message in errors.email, which renders it. setFocus("email") moves focus to the field so the label and description are read.