Sub topic 16
Accessible error messages
This chapter assumes you know the built-in validation attributes, the Constraint Validation API (validity, setCustomValidity), and the way a label names a control. It covers how to show validation errors so that keyboard and screen reader users can find, hear, and fix them.
Why the default bubbles are not enough
When a browser blocks a submission, it shows a native bubble next to the first invalid control. The bubble disappears when focus moves or after a few seconds. Its wording and styling differ between browsers, and you can't control it. Screen readers announce it inconsistently. It also only covers the first problem, so a user with four errors finds them one at a time.
Persistent error text that you render yourself fixes these problems. You take over by adding novalidate to the form, which turns off the browser's bubbles and submit blocking. The validation itself still works. control.validity, checkValidity(), and validationMessage keep working, so you reuse the same constraints and only change how errors are presented.
The working model
An accessible error has four parts:
- Visible text that says what is wrong and how to fix it.
- A programmatic link between that text and the control, made with
aria-describedby. - A state on the control,
aria-invalid="true", so assistive technology reports it as invalid. - A way to get the user to the problem: moving focus to an error summary or to the first invalid control.
| Technique | What it does | When to use it |
|---|---|---|
| `aria-describedby` | Adds the error text to the control's description, read after its name | Every field error |
| `aria-invalid="true"` | Marks the control as invalid | Only while the field has an error |
| Error summary with links | Lists all errors in one place at the top of the form | On failed submit |
| `role="alert"` or `aria-live` | Announces text that changes without a focus move | Inline errors shown while typing or on blur |
| Focus management | Moves the user to the first problem | On failed submit |
A complete example
The HTML gives each field an empty error paragraph that already exists in the page. The control points to both its hint and its error with aria-describedby.
<form id="signup" action="/signup" method="post" novalidate>
<div id="error-summary" tabindex="-1" hidden>
<h2>There is a problem</h2>
<ul></ul>
</div>
<div class="field">
<label for="email">Email address</label>
<p id="email-hint">We only use it to send your receipt.</p>
<input id="email" name="email" type="email" autocomplete="email"
required aria-describedby="email-hint email-error">
<p id="email-error" class="error"></p>
</div>
<div class="field">
<label for="password">Password</label>
<input id="password" name="password" type="password"
autocomplete="new-password" required minlength="8"
aria-describedby="password-error">
<p id="password-error" class="error"></p>
</div>
<button type="submit">Create account</button>
</form>
<style>
.error { color: #b00020; margin: 0.25rem 0 0; }
.error:empty { display: none; }
input[aria-invalid="true"] { border: 2px solid #b00020; }
</style>The script turns validity states into messages, writes them next to the controls, builds the summary, and moves focus.
const form = document.querySelector('#signup');
const summary = document.querySelector('#error-summary');
const summaryList = summary.querySelector('ul');
const messages = {
email: {
valueMissing: 'Enter your email address.',
typeMismatch: 'Enter an email address like [email protected].',
},
password: {
valueMissing: 'Enter a password.',
tooShort: 'Password must be at least 8 characters.',
},
};
function messageFor(control) {
const rules = messages[control.id] ?? {};
for (const key in rules) {
if (control.validity[key]) return rules[key];
}
return control.validationMessage;
}
function setError(control, text) {
const error = document.getElementById(`${control.id}-error`);
error.textContent = text;
if (text) {
control.setAttribute('aria-invalid', 'true');
} else {
control.removeAttribute('aria-invalid');
}
}
form.addEventListener('submit', (event) => {
summaryList.replaceChildren();
const invalid = [];
for (const control of form.elements) {
if (!control.willValidate) continue;
if (control.validity.valid) {
setError(control, '');
} else {
const text = messageFor(control);
setError(control, text);
invalid.push({ control, text });
}
}
if (invalid.length === 0) {
summary.hidden = true;
return;
}
event.preventDefault();
for (const { control, text } of invalid) {
const link = document.createElement('a');
link.href = `#${control.id}`;
link.textContent = text;
link.addEventListener('click', (e) => {
e.preventDefault();
control.focus();
});
const item = document.createElement('li');
item.append(link);
summaryList.append(item);
}
summary.hidden = false;
summary.focus();
});
form.addEventListener('input', (event) => {
const control = event.target;
if (control.getAttribute('aria-invalid') === 'true') {
setError(control, control.validity.valid ? '' : messageFor(control));
}
});Some details in this code matter:
summaryhastabindex="-1", so script can focus it but it is not in the Tab order. Focusing it makes a screen reader read the heading and then the list of links. That is how the user learns how many problems exist.- The
inputhandler only revalidates fields that are already marked invalid. Users who haven't finished typing aren't shown errors, and corrected fields clear immediately. form.elementsincludes buttons and fieldsets.willValidateisfalsefor those, so they are skipped.tooShortis only reported after the user has edited the value. A password set by script or autofill that is too short may still passminlengthin some browsers. The server must check anyway.
Writing the message
Messages should say what to do, not only what is wrong. "Enter an email address like [email protected]" works better than "Invalid input". Put the message next to the field, and name the field in the summary text, because the summary is read out of context. Don't rely on red alone. The text itself carries the meaning, and you can add an icon or a prefix such as "Error:" for users who can't tell the colours apart.
The title attribute is not a substitute for error text. It is hover-only for mouse users and unreliable for touch and keyboard users.
Live regions for inline errors
Focus moves are right on submit. For errors that appear while the user stays in the field, for example on blur, you can announce the text with a live region. The region must be in the DOM before its content changes. A region inserted together with its text is often not announced.
<p id="email-error" class="error" role="alert"></p>Use role="alert" sparingly. It interrupts speech, so many alerts at once make the page noisy. Don't use it on every field in a submit pass if you also move focus to the summary, or users will hear everything twice. The summary alone is enough in that case.
Common errors
- Replacing
aria-describedbyinstead of adding to it. If you set it to the error id only, the hint is lost. Keep the hint id in the list. - Leaving
aria-invalid="true"after the fix. Remove it when the field becomes valid. Don't set it on page load for fields the user hasn't touched. - Showing errors only in a bubble or tooltip. These vanish and can't be reviewed.
- Using a placeholder as the message. Placeholders disappear when the user types and have low contrast.
- Summary links that go nowhere. If the
hrefpoints to an id that doesn't exist, or the label'sfordoesn't match the control, the link does nothing. Link to the control'sid, and move focus in script as above. - Hiding the error with
display: nonewhile the control still references it. Hidden text referenced byaria-describedbycan still be read. An empty element that is hidden by:emptyavoids that problem. - Validating on every keystroke from the first character. The user hears "Invalid email" while typing
a. Validate on blur or on submit first, then live once the field is flagged.
Exercise
Your form has an email field with the hint "We only use it for your receipt" (id email-hint) and an error paragraph (id email-error). Write the value of aria-describedby on the input so a screen reader reads both, and explain when aria-invalid should be set.
Show answer
aria-describedby="email-hint email-error". Both ids are listed, separated by a space, so the hint and the error are both read after the field's label. Set aria-invalid="true" only while the field has an error, and remove it as soon as the value becomes valid. Don't set it on a field the user hasn't interacted with.
Exercise
After a failed submit, your script writes errors beside each field and also puts role="alert" on every error paragraph, and focuses the error summary. Users report hearing every message twice. What is the cause and the fix?
Show answer
The alert regions announce each message when its text is written, and the summary announces them again when it receives focus. Remove role="alert" from the inline paragraphs for the submit case and rely on the focused summary. Keep a live region only for errors that appear while the user stays in a field.