Sub topic 11
Accessible labels and error messages
This chapter assumes you can build a controlled form with useState, write a validate function that returns an errors object, and handle onSubmit with preventDefault. It adds the accessibility layer: every field needs a programmatic label, and every error needs a programmatic link to the field it describes.
Why accessibility belongs in form code
A sighted user sees that an error message sits under a field. A screen reader user does not. The browser exposes a form to assistive technology through the accessibility tree, and that tree knows about relationships only if your markup declares them. If an error is a loose <p> next to an input, a screen reader will not announce it when the user focuses the field.
Accessible forms also help everyone else:
- Clicking a label focuses its input, which makes small targets such as checkboxes easier to hit.
- Voice control software can activate a field by saying its label.
- Keyboard users get predictable focus order.
- Password managers and browser autofill use labels and
autocompletehints to fill fields correctly.
Two jobs follow from this. First, give each control an accessible name. Second, tie each error message to its control and make sure the error is announced.
Labels: giving each control a name
An accessible name is the text a screen reader speaks when focus lands on a control. For inputs, the best source is a <label> element. There are two ways to associate one.
Wrapping
Place the input inside the label. This is the pattern used in the first controlled-input example.
<label>
Name
<input value={name} onChange={(e) => setName(e.target.value)} />
</label>No id is needed. It works well for simple cases, but it makes it harder to style the label and the input separately.
Using htmlFor and id
Give the input an id and point the label at it with htmlFor. React uses htmlFor because for is a reserved word in JavaScript.
<label htmlFor="email">Email</label>
<input id="email" name="email" value={values.email} onChange={handleChange} />The id must be unique on the page. This is where reusable components go wrong. If you render a TextField component twice and hard-code id="email" inside it, the second label points at the first input. Use useId, which React provides for exactly this case.
import { useId } from 'react';
function TextField({ label, error, ...inputProps }) {
const id = useId();
const errorId = `${id}-error`;
return (
<div>
<label htmlFor={id}>{label}</label>
<input
id={id}
aria-invalid={Boolean(error)}
aria-describedby={error ? errorId : undefined}
{...inputProps}
/>
{error && <p id={errorId}>{error}</p>}
</div>
);
}useId returns a string that is stable between server and client rendering and unique per call. Do not use it as a list key, and do not use Math.random() for ids, because the value would change on every render and break hydration.
Labels are not placeholders
A placeholder is hint text that disappears as soon as the user types. It has weak support as an accessible name, often has low contrast, and leaves users unable to check what a field was for after they fill it in. Keep a visible label and use the placeholder, if at all, for a format example.
If a design truly cannot show a label, use aria-label on the input as a fallback. A visible <label> is still the better choice, because aria-label is invisible to sighted users and is often missed by automatic translation tools.
Radios and checkboxes in groups
A group of radios needs a name for the group as well as for each option. Use <fieldset> with a <legend>.
<fieldset>
<legend>Plan</legend>
<label>
<input type="radio" name="plan" value="free" checked={form.plan === 'free'} onChange={handleChange} />
Free
</label>
<label>
<input type="radio" name="plan" value="pro" checked={form.plan === 'pro'} onChange={handleChange} />
Pro
</label>
</fieldset>A screen reader announces something like "Plan, group. Free, radio button, 1 of 2." Without the legend, the user hears "Free" with no idea what is being chosen.
Connecting errors to fields
The login form in this tutorial's validation example uses two attributes on each input.
<input
id="email"
name="email"
value={values.email}
onChange={handleChange}
aria-invalid={Boolean(errors.email)}
aria-describedby={errors.email ? 'email-error' : undefined}
/>
{errors.email && <p id="email-error">{errors.email}</p>}aria-invalid="true"tells assistive technology the current value is not acceptable. Screen readers typically announce "invalid entry" when the field is focused.aria-describedbypoints to theidof an element whose text supplies a description. The screen reader reads the label first, then the control type, then the description. For an invalid email field the user hears something like "Email, edit text, invalid entry, Enter a valid email address."
In JSX, aria-invalid={false} renders aria-invalid="false", which is valid. Passing undefined omits the attribute. Both are fine for a field with no error.
The conditional on aria-describedby matters. If you point it at an id that does not exist in the DOM, nothing breaks, but the reference is dead. Setting it to undefined when there is no error keeps the markup clean.
You can reference more than one element by separating ids with a space. This is useful when a field has both a permanent hint and an error.
<input
id="password"
type="password"
aria-describedby={`password-hint ${errors.password ? 'password-error' : ''}`.trim()}
/>
<p id="password-hint">Use at least 8 characters.</p>
{errors.password && <p id="password-error">{errors.password}</p>}Announcing errors
aria-describedby helps when a user focuses a field. It does not announce anything by itself when an error first appears after a submit. There are two common ways to close that gap.
Move focus to the first invalid field
After a failed submit, focus the first field with an error. The screen reader then reads the label, the invalid state and the error text. This needs a ref and a small effect or an imperative call in the submit handler.
import { useRef, useState } from 'react';
function validate(values) {
const errors = {};
if (!values.email.includes('@')) errors.email = 'Enter a valid email address.';
if (values.password.length < 8) errors.password = 'Use at least 8 characters.';
return errors;
}
export default function LoginForm() {
const [values, setValues] = useState({ email: '', password: '' });
const [errors, setErrors] = useState({});
const fieldRefs = useRef({});
function handleChange(e) {
setValues((prev) => ({ ...prev, [e.target.name]: e.target.value }));
}
function handleSubmit(e) {
e.preventDefault();
const nextErrors = validate(values);
setErrors(nextErrors);
const firstInvalid = Object.keys(nextErrors)[0];
if (firstInvalid) {
fieldRefs.current[firstInvalid]?.focus();
return;
}
console.log('Valid', values);
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
ref={(el) => (fieldRefs.current.email = el)}
value={values.email}
onChange={handleChange}
aria-invalid={Boolean(errors.email)}
aria-describedby={errors.email ? 'email-error' : undefined}
/>
{errors.email && <p id="email-error">{errors.email}</p>}
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
ref={(el) => (fieldRefs.current.password = el)}
value={values.password}
onChange={handleChange}
aria-invalid={Boolean(errors.password)}
aria-describedby={errors.password ? 'password-error' : undefined}
/>
{errors.password && <p id="password-error">{errors.password}</p>}
<button type="submit">Log in</button>
</form>
);
}The object keys follow insertion order, and validate adds email before password, so the first key is the first field on the page. If your validation order differs from the visual order, the focus will jump to the wrong place, so keep them aligned.
Use a live region
A live region is an element whose content changes are announced without moving focus. role="alert" is the assertive form, and role="status" is the polite one. A summary at the top of the form is a common use.
<div role="alert">
{Object.keys(errors).length > 0 && `The form has ${Object.keys(errors).length} errors.`}
</div>For reliable announcements, the live region element should already exist in the DOM before its text changes. If you render the whole <div role="alert"> only when errors appear, some screen reader and browser pairs will stay silent. Keep the container mounted and change only its contents.
Putting role="alert" on every inline error message is tempting. On a submit that produces five errors, the screen reader may read all five over each other. Prefer focus on the first invalid field, optionally with a one-line summary in a live region.
Showing errors at the right time
Errors shown as the user types the first character of an email are noise and are announced mid-keystroke. Two timing strategies work well:
- Validate on submit, then re-validate on change once a field has been submitted with an error.
- Track touched fields and show an error only after the user leaves the field (
onBlur).
Whichever you choose, keep the accessible behavior consistent: the error text, aria-invalid and aria-describedby should all appear and disappear together, driven by the same condition. A single const showError = touched.email && errors.email; used for all three avoids mismatches.
Native validation versus custom messages
The noValidate attribute on the form turns off the browser's built-in validation bubbles, so your own messages take over. This is the right choice when you need consistent wording and the linked error pattern above. If you leave native validation on, required, type="email" and minLength give you free checks and accessible messages with no extra code. Do not mix the two on the same field without a plan, because the browser may block submit before your handler runs.
If you mark fields as required, say so in text as well as with an asterisk. A lone * is read inconsistently. Add the required attribute, or aria-required="true" when you handle validation yourself, and explain the convention near the top of the form.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Placeholder used as the only label | No stable name, text vanishes on input | Add a visible `<label>` |
| Hard-coded `id` in a reusable component | Labels attach to the wrong input | Generate ids with `useId` |
| Error text with no `aria-describedby` | Screen reader never reads the error on focus | Link the message by id |
| `aria-invalid` stays `true` after the fix | Field is announced as invalid when it is valid | Derive it from the current errors |
| Conditionally mounted `role="alert"` container | Message is sometimes not announced | Keep the container in the DOM |
| Color as the only error signal | Users with color blindness miss it | Add text, and optionally an icon |
| Radios without `<fieldset>` and `<legend>` | Group purpose is unknown | Wrap the group |
How the pieces connect
Testing what you built
Automated tools catch only some problems, so combine three checks:
- Tab through the form with only the keyboard. Every control must be reachable, show a visible focus outline, and work with Space or Enter.
- Click each label. The matching input should take focus.
- Turn on a screen reader (VoiceOver on macOS, NVDA on Windows) and submit an empty form. Confirm that you hear the label, the invalid state and the error text.
For tests in code, Testing Library encourages the accessible approach. getByLabelText('Email') fails if your label is not connected, which makes it a cheap regression check. expect(input).toHaveAccessibleDescription('Enter a valid email address.') from jest-dom checks the aria-describedby link directly.
Exercise
A reusable TextField component hard-codes id="field" on its input and renders a matching label with htmlFor="field". The page shows two TextField components. What goes wrong when a user clicks the second label, and what is the fix?
Show answer
Ids must be unique, so both labels point to the first element with id="field". Clicking the second label focuses the first input, and screen readers give the second input no correct name. The fix is to generate a unique id per instance with useId and use it for both the input id and the label htmlFor (and for derived ids such as the error message).
Exercise
A form shows an error paragraph under the email input after a failed submit, but a screen reader user focusing the input hears only "Email, edit text". Which two attributes are missing, and how should each be set?
Show answer
Add aria-describedby on the input with the id of the error paragraph (set it to undefined when there is no error), and aria-invalid={Boolean(errors.email)}. The paragraph needs a matching id such as email-error.
Exercise
After a failed submit, you want a screen reader user to hear the problem right away without a live region on every message. What approach does this chapter recommend, and what must stay true about the order of your errors?
Show answer
Move focus to the first invalid field in the submit handler, using a ref. The screen reader then reads its label, invalid state and error text. The order of keys in the errors object must match the visual order of the fields, or focus will land on the wrong field.