Sub topic 12
Making errors accessible: aria-describedby, error summary, focus
This chapter assumes you can write basic HTML forms, know what a label is, and can read short JavaScript event handlers. It also assumes you have seen the chapters on writing error messages and showing errors visually. Here the goal is different: make sure an error that a sighted mouse user can see is also available to a keyboard user and a screen reader user.
Why visible errors are not enough
A red border and a message below a field work for people who can see the page. A screen reader user moves through the page by element. The reader announces the field's label and type, but it does not announce text that sits near the field unless the browser has been told the two are related. A keyboard user who submits the form may also have focus on a button at the bottom of the page, far from the problem.
Three things fix this:
- Link each error message to its field, so the message is read with the field.
- Mark the field as invalid, so its state is announced.
- Move focus to something that tells the user what went wrong, after a failed submit.
Linking the message to the field with aria-describedby
aria-describedby is an attribute that holds the id of another element. The browser exposes that element's text as the field's accessible description. Most screen readers read the label first, then the type, then the description.
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email"
required aria-invalid="true" aria-describedby="email-error">
<p id="email-error">Error: Enter an email address in the format [email protected]</p>A screen reader typically reads this as: "Email address, edit text, invalid entry, Error: Enter an email address in the format [email protected]". The exact wording varies by reader.
Some details matter:
- The message must be in the page, in the accessibility tree, when the field is read. An element with
hiddenordisplay: noneis skipped, even whenaria-describedbypoints to it. Showing the message by removinghiddenfixes this. aria-describedbyaccepts several ids separated by spaces. If the field already has hint text, keep it and add the error id, so the user hears both.- The text of the error is read as part of the description, so write it as a full sentence that makes sense without the visual layout around it.
<label for="postcode">Postcode</label>
<p id="postcode-hint">For example, SW1A 1AA</p>
<input id="postcode" name="postcode" type="text" autocomplete="postal-code"
aria-invalid="true" aria-describedby="postcode-hint postcode-error">
<p id="postcode-error">Error: Enter a postcode in the correct format</p>The order of ids is the order of reading. Putting the error first is a reasonable choice, because it is the new information.
Why the "Error:" prefix
The visible word "Error:" at the start of the message does two jobs. It makes the message identifiable when color is not seen, which supports the previous chapter's rule about not relying on color. It also tells a screen reader user that this description is a problem and not a hint. Some teams add a visually hidden "Error:" instead when the design has an icon. Either approach is fine, as long as the word is in the text.
Marking the field with aria-invalid
aria-invalid="true" tells assistive technology that the current value is not acceptable. Screen readers announce it as "invalid entry" or similar.
Rules of thumb:
- Set it only after the field has been validated and found wrong. Do not put
aria-invalid="true"on an empty required field on page load, because the user has not done anything wrong yet. - Remove it, or set it to
false, when the problem is fixed. A stalearia-invalidis a false alarm. - Remove the error id from
aria-describedbyat the same time. The earlier example'sshowErrorfunction does this for you. aria-invaliddoes not replace the error text. It states that something is wrong, not what.
The browser's own validation state (:invalid, validity) is separate from aria-invalid. When you use native required and type="email" without novalidate, the browser shows its own bubble and handles some accessibility. Most custom designs set novalidate on the form, because browser messages are hard to style and word, and then take over the whole job. If you do that, you must supply every piece in this chapter yourself.
Live regions: when you need them, and when you do not
An aria-live region or role="alert" makes a screen reader announce text when it changes, without moving focus. It is tempting to give every error message role="alert". This causes problems on a form with several errors, because all of them are announced at once, interrupting each other and whatever the user is typing.
Use this guide:
| Situation | Approach |
|---|---|
| Error appears when the user leaves a field (blur) | Update the description with `aria-describedby`. The user hears it when they return to the field. Optionally use one polite live region for a short status. |
| Error appears on submit | Move focus to the error summary. Do not also use `role="alert"` on every message. |
| Error appears while typing | Avoid announcing each keystroke. Wait until the user pauses or leaves the field. |
If you add a live region, it must exist in the page before its content changes. Inserting an element that already has role="alert" is unreliable in some readers.
The error summary
On submit, a form with several errors needs a place where the user learns the full list. An error summary is a block at the top of the form or page that lists every error, each as a link to the field that has it.
<div id="error-summary" tabindex="-1" role="group" aria-labelledby="error-summary-title">
<h2 id="error-summary-title">There is a problem</h2>
<ul>
<li><a href="#email">Enter an email address in the format [email protected]</a></li>
<li><a href="#postcode">Enter a postcode in the correct format</a></li>
</ul>
</div>Points to check:
- The summary has a heading. Screen reader users can find it through heading navigation. "There is a problem" is plain and works.
tabindex="-1". Adivcannot normally receive focus.tabindex="-1"lets a script call.focus()on it without adding it to the Tab order.- Each link text is the error message. Use the same wording as the message beside the field. Avoid "Field 1 is wrong" or "Click here".
- Each link goes to the field's
id. Following the link moves the user to the control. In some browsers, a link to a fragment moves the viewport but not keyboard focus, so add a click handler that calls.focus()on the target. - Do not use role="alert" on the whole summary and also move focus to it. One mechanism is enough. Focus is more dependable, and it also puts keyboard users in the right place.
Managing focus after a failed submit
Focus is the point where keyboard input and the screen reader's attention are. After a failed submit, the page must put it somewhere useful, or the user has to search for the problem.
There are two common patterns.
- Focus the error summary. It reads the heading and the list, and the user then follows a link. This works well for forms with more than one or two fields.
- Focus the first invalid field. This is quick and works for short forms. The user hears the label, the invalid state, and the error description at once. The downside is that the user does not learn about the other errors until they get to them.
The chapter's validation example used the second pattern. Here is a fuller version that uses the summary, builds its list from the invalid fields, and makes the links move focus.
// Assumes <form novalidate>, and an empty <div id="error-summary" tabindex="-1" hidden>
// before the form's fields. Each field has a <p id="FIELD-error" hidden> after it.
const form = document.querySelector('form');
const summary = document.getElementById('error-summary');
function messageFor(input) {
if (input.validity.valueMissing) {
return 'Enter ' + (input.dataset.name || 'a value');
}
if (input.validity.typeMismatch) {
return 'Enter ' + (input.dataset.name || 'a value') + ' in the correct format';
}
return input.validationMessage;
}
function setFieldError(input, message) {
const error = document.getElementById(input.id + '-error');
error.textContent = message ? 'Error: ' + message : '';
error.hidden = !message;
if (message) {
input.setAttribute('aria-invalid', 'true');
input.setAttribute('aria-describedby', error.id);
} else {
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedby');
}
}
function renderSummary(invalidFields) {
summary.replaceChildren();
const heading = document.createElement('h2');
heading.textContent = 'There is a problem';
const list = document.createElement('ul');
for (const input of invalidFields) {
const item = document.createElement('li');
const link = document.createElement('a');
link.href = '#' + input.id;
link.textContent = messageFor(input);
link.addEventListener('click', (event) => {
event.preventDefault();
input.focus();
});
item.appendChild(link);
list.appendChild(item);
}
summary.append(heading, list);
summary.hidden = false;
}
form.addEventListener('submit', (event) => {
const invalidFields = [...form.elements].filter(
(el) => el.willValidate && !el.checkValidity()
);
for (const el of form.elements) {
if (el.willValidate) {
setFieldError(el, el.checkValidity() ? '' : messageFor(el));
}
}
if (invalidFields.length > 0) {
event.preventDefault();
renderSummary(invalidFields);
summary.focus();
} else {
summary.hidden = true;
}
});This script uses a data-name attribute, such as data-name="your email address", to build readable messages. Without it, the fallback is generic, so set it on every required field.
Gotchas with focus
- Hidden elements cannot take focus. Remove
hiddenbefore calling.focus(). The code above setssummary.hidden = falsefirst. - Scrolling.
.focus()scrolls the element into view in most browsers. If a sticky header covers it, addscroll-margin-topto the summary and the fields in CSS. - Do not move focus on blur. If an error appears when the user tabs out of a field, and your code sends focus back to that field, the user is trapped. Show the message, and leave focus where the user put it.
- Do not move focus while the user is typing. It interrupts them and may clear what they typed.
- Single-page apps. If the form is replaced by a new view after submit, focus is lost to the top of the document. Set it deliberately.
- Page title. On a full page reload with errors, prefix the
titlewith "Error:" so the screen reader announces the problem as the page loads.
What the flow looks like
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Error text placed near the field with no `aria-describedby` | Screen reader users never hear it | Add `aria-describedby` pointing to the message id |
| Message inside an element with `hidden` or `display: none` | Message is skipped | Show the message element before expecting it to be read |
| `aria-invalid="true"` on page load | Every field is announced as invalid | Set it only after validation fails |
| `aria-invalid` and `aria-describedby` left after the fix | Reader keeps announcing an old error | Remove both when the value becomes valid |
| `role="alert"` on every message | Announcements overlap and interrupt | Use focus on the summary, or one polite live region |
| Focus stays on the submit button | Keyboard users do not find the errors | Focus the summary or first invalid field |
| Summary links go to a non-existent id | Link does nothing | Match each `href` to a real field `id` |
| Message only says "Invalid" | User cannot fix it | Name the problem and the fix, as in the earlier chapter |
Testing this chapter's work
You can check most of it in a few minutes.
- Put the mouse away. Fill the form wrongly and press Enter. Focus should land on the summary or the first invalid field.
- Press Tab through the summary links. Each one should move focus into the matching field.
- Turn on a screen reader and move into an invalid field. You should hear the label, the invalid state, and the message.
- Fix one error and move on. The message and
aria-invalidshould be gone. - Inspect a field in the browser's accessibility panel and read its Description. It should show the error text.
Exercise
A form has three invalid fields after submit. The developer gives each error paragraph role="alert" and leaves focus on the submit button. Name two problems this causes for screen reader and keyboard users, and describe a better approach.
Show answer
First, the three alerts are announced at nearly the same time and interrupt each other, so the user may hear only part of the messages. Second, focus stays on the submit button, so keyboard users must search the page to find the errors, and the alerts do not tell them where each one is. A better approach is to build an error summary with a heading and one link per error, move focus to it after the failed submit, and link each field to its own message with aria-describedby and aria-invalid="true". Remove role="alert" from the individual messages.
Exercise
A field has a hint with id phone-hint. Validation fails and the error paragraph has id phone-error. Write the aria-describedby value so that the user hears the error first and then the hint, and say what must happen to the attribute once the user fixes the value.
Show answer
aria-describedby="phone-error phone-hint". When the value becomes valid, remove phone-error from the attribute (leaving aria-describedby="phone-hint"), remove aria-invalid, and hide or empty the error paragraph, so the screen reader no longer reports the old problem.
Exercise
Why does the summary div in this chapter have tabindex="-1", and why does the script remove hidden from it before calling focus()?
Show answer
A div is not focusable by default. tabindex="-1" makes it focusable from script without adding it to the Tab order. An element with hidden is not rendered, so it cannot receive focus, which means hidden must be removed first or focus() does nothing.