Sub topic 9
Accessible inline error messages
This chapter assumes you can build a form with labels and inputs, read a control's validity object, and write basic event handlers. Earlier chapters showed how to turn off the browser's default error bubbles with novalidate and how to read validationMessage. Here you will make the replacement messages work for people who use screen readers, keyboard navigation, magnification, or who have color vision deficiency.
Why default bubbles are not enough
Browser validation bubbles disappear when focus moves, they cannot be styled, and their screen reader support varies between browsers. Once you set novalidate and draw your own messages, you take on the work the browser used to do. Four things must hold:
- The message is visible next to the field it describes.
- Assistive technology can tell which message belongs to which field.
- Assistive technology is told when a field becomes invalid and when the message changes.
- Keyboard focus lands somewhere useful after a failed submit.
Painting red text under a field satisfies only the first.
The pieces of an accessible error
Four mechanisms do most of the work.
| Mechanism | What it does | Where it goes |
|---|---|---|
| `<label for>` | Gives the control its accessible name | Every control, always |
| `aria-describedby` | Links the control to the element holding the error text | The control |
| `aria-invalid="true"` | Tells assistive technology the current value is not accepted | The control, only while invalid |
| Focus move or live region | Makes sure the user notices the change | Script behavior |
Keep the label and the error separate. The label says what the field is. The error says what is wrong. If you put the error inside the label, the field's name changes every time validation runs, and that is confusing.
Markup: an error container that always exists
Create the error element in the HTML, next to the field, and link it from the start.
<div class="field">
<label for="email">Email</label>
<input id="email" name="email" type="email" required
autocomplete="email" aria-describedby="email-error">
<p id="email-error" class="error"></p>
</div>An empty element referenced by aria-describedby contributes nothing to the description, so linking it before any error exists is harmless. This is easier than adding and removing the attribute. It also means the container is already in the page when you fill it, which matters for live regions (see below).
If the field also has hint text, list both ids, separated by a space. The order is the reading order.
<input id="username" name="username" required minlength="3"
aria-describedby="username-hint username-error">
<p id="username-hint">3 to 20 lowercase letters, digits, or underscores.</p>
<p id="username-error" class="error"></p>Script: show and clear errors
Put the three steps (write text, set state, clear both) in two small functions so every validation path behaves identically.
function showError(field, message) {
const error = document.getElementById(`${field.id}-error`);
error.textContent = message;
field.setAttribute('aria-invalid', 'true');
}
function clearError(field) {
const error = document.getElementById(`${field.id}-error`);
error.textContent = '';
field.removeAttribute('aria-invalid');
}
function validateField(field) {
if (field.validity.valid) {
clearError(field);
return true;
}
showError(field, field.validationMessage);
return false;
}
const form = document.getElementById('signup');
form.noValidate = true;
form.addEventListener('submit', (event) => {
let firstInvalid = null;
for (const field of form.elements) {
if (!field.willValidate || !document.getElementById(`${field.id}-error`)) continue;
if (!validateField(field)) firstInvalid ??= field;
}
if (firstInvalid) {
event.preventDefault();
firstInvalid.focus();
}
});Three details are easy to get wrong.
- Remove
aria-invalidwhen the field is valid. Do not set it to"false"on page load. Some screen readers announce "invalid" for the value you set at any time, and a field that has not been touched is not invalid. validationMessageis browser text. It is localized to the browser's language, not the page's language. If your page is in a different language from the browser, set your own text withsetCustomValidityor a lookup keyed onfield.validityflags.- Fields with no error element are skipped. Buttons and fieldsets are in
form.elementstoo. The guard avoids anullerror.
Getting the error announced
Screen readers read a field's name, role, state, and description when focus enters it. That gives you the first and most reliable way to announce an error: move focus to the first invalid field. The user hears something like "Email, edit text, invalid entry, Enter a valid email address." The aria-invalid state and the linked description do the work, and no extra markup is needed.
That covers submit. It does not cover errors that appear while focus stays in a field, for example when you validate as the user types or on blur. In that case focus is not moving, so nothing is read. You have two options:
- Make the error container a polite live region:
<p id="email-error" class="error" aria-live="polite"></p>. When its text changes, the screen reader announces the new text without moving focus. - Skip live validation and validate on submit only.
A live region only announces changes made after it is in the page. This is why the container should exist in the HTML, not be created together with its text. Creating the element and filling it in the same moment is often not announced at all.
Validate when?
Timing is the most common usability mistake after hiding the error from assistive technology.
- On submit is always correct and always needed.
- On
blur(leaving the field) is a good second trigger, but only for fields the user has actually edited. Validating an empty required field the moment someone tabs through it produces errors for fields they have not reached yet. - On
inputis right for clearing an error as soon as the value becomes valid, but not for showing one. Telling someone their email is invalid after they type the first letter is noise.
A pattern that works: show errors on blur or submit, and re-check on input only if the field is already marked invalid.
for (const field of form.elements) {
if (!field.willValidate || !document.getElementById(`${field.id}-error`)) continue;
field.addEventListener('blur', () => {
if (field.value !== '') validateField(field);
});
field.addEventListener('input', () => {
if (field.getAttribute('aria-invalid') === 'true') validateField(field);
});
}The blur handler skips empty fields so that tabbing past an untouched field is silent. Submit still catches required fields that were never filled.
Error summary for long forms
On a form with many fields, focusing only the first invalid field hides how many problems exist. A summary at the top lists every error with a link to the field. Focus goes to the summary, and each link jumps to its field.
<div id="error-summary" tabindex="-1" hidden>
<h2>There are problems with your form</h2>
<ul id="error-list"></ul>
</div>const summary = document.getElementById('error-summary');
const list = document.getElementById('error-list');
function renderSummary(invalidFields) {
list.replaceChildren();
for (const field of invalidFields) {
const label = document.querySelector(`label[for="${field.id}"]`);
const link = document.createElement('a');
link.href = `#${field.id}`;
link.textContent = `${label.textContent}: ${field.validationMessage}`;
const item = document.createElement('li');
item.append(link);
list.append(item);
}
summary.hidden = invalidFields.length === 0;
if (invalidFields.length) summary.focus();
}The tabindex="-1" makes the container focusable from script without adding it to the Tab order. Collect the invalid fields in your submit handler, call renderSummary(invalidFields), and focus the summary instead of the first field. Keep the inline messages too: the summary is for orientation, and the inline message is what the user sees while fixing the field.
Build the summary with textContent, as shown, not innerHTML. Messages can include user input, and inserting it as markup is a cross-site scripting risk.
Do not rely on color
A red border alone fails users with color vision deficiency and anyone using a high-contrast mode that overrides your colors. Every error needs text. It helps to add an icon or a prefix such as "Error:" in the message, and to keep a text contrast ratio of at least 4.5:1 against the background. Do not hide the message on :focus or reveal it only on hover.
Common errors
- Using
titleas the error. Browsers exposetitleinconsistently, and it is not shown on touch devices. Use it for thepatternhint, if at all, never as your only message. - Pointing
aria-describedbyat an id that does not exist. The link silently fails. Check the id spelling in your tests. - Reusing one error element for several fields. Each control needs its own, or the descriptions overlap.
- Hiding errors with
display: noneand then expecting them to be read. Content hidden this way is removed from the accessibility tree. Clear the text instead and leave the empty container in place. - Moving focus on every keystroke. Focus changes are for submit, not for live feedback.
- Writing vague messages. "Invalid input" says nothing. Say what is wrong and what is expected: "Use 3 to 20 lowercase letters, digits, or underscores."
Exercise
A user tabs through a form without typing anything, then presses Submit. Your code runs validation on blur for every field and sets role="alert" on every error element. What two problems will a screen reader user hit, and what is the fix for each?
Show answer
First, validating on blur reports "required" errors for fields the user has not edited, so errors appear before they could have done anything. Fix: on blur, only validate fields whose value is not empty, and let submit catch the required fields. Second, with role="alert" on every error element, the submit fills them all at once and the screen reader interrupts itself to read each message without the field name, then reads the first field again when focus moves. Fix: remove role="alert", set aria-invalid and aria-describedby on the controls, and move focus to the first invalid field (or to an error summary). Use aria-live="polite" only on errors that appear while focus stays in a field.
Exercise
Why is it better to include the aria-describedby attribute in the HTML from the start, pointing at an empty error element, than to add both the element and the attribute when the first error occurs?
Show answer
A live region only announces changes made to content that is already in the page, so an element created together with its text may not be announced. An empty element that is already linked adds nothing to the field's description, so it causes no noise. Writing text into it later makes the description current the next time the field is read, and with aria-live="polite" it is announced immediately. It also removes the need to add and remove the attribute, which is one less place for the state to go out of sync.