Sub topic 9
Accessible inline error messages
This chapter assumes you know the Constraint Validation API (validity, validationMessage, setCustomValidity), basic ARIA attributes, and how to handle submit and blur events. Here you will turn a validation result into an error message that sighted users, keyboard users, and screen reader users can all find and understand.
Why default bubbles are not enough
Browser validation bubbles disappear quickly, vary between browsers, and may not be announced consistently by assistive technology. They also vanish when focus moves, so a user cannot refer back to them. An inline message stays in the page, can be styled, and can be linked to its field.
Once you show your own messages, set form.noValidate = true so the browser does not also show its bubble. You then have to do the accessibility work yourself.
The four parts of an accessible error
- Text, not just color. A red border alone fails users with color blindness. Write the problem and how to fix it ("Use 3 to 20 lowercase letters, digits, or underscores.").
- A programmatic link.
aria-describedbyon the control points to the element holding the message. A screen reader then reads the label, the state, and the message when the field gets focus. - An invalid state.
aria-invalid="true"tells assistive technology the current value is wrong. Remove it when the value is fixed. - Focus management. After a failed submit, move focus to the first invalid field so the message is read immediately.
Markup
Give every field a message container that exists in the page from the start. Elements that are present at load are announced more reliably than elements inserted later and referenced afterward.
<form id="signup" action="/signup" method="post">
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+"
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>
<button type="submit">Sign up</button>
</form>aria-describedby accepts several IDs separated by spaces. Listing both the hint and the error keeps the instructions available while the error is shown. An empty error element adds nothing to the spoken description.
Script
This helper writes or clears one message and keeps aria-invalid in sync.
const form = document.getElementById('signup');
form.noValidate = true;
function showError(field, message) {
const error = document.getElementById(`${field.id}-error`);
error.textContent = message;
if (message) {
field.setAttribute('aria-invalid', 'true');
} else {
field.removeAttribute('aria-invalid');
}
}
function validateField(field) {
showError(field, field.validity.valid ? '' : field.validationMessage);
return field.validity.valid;
}
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();
}
});
form.addEventListener('focusout', (event) => {
if (event.target.matches('input') && event.target.value !== '') {
validateField(event.target);
}
});The focusout listener validates a field when the user leaves it, but only if it has a value. Validating on every keystroke shows "invalid email" while the user is still typing, which is noisy for everyone and worse with a screen reader.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Message is not linked with `aria-describedby` | Screen reader users never hear it | Reference the message ID on the control |
| `aria-describedby` replaced by the error ID only | The hint is lost | List both IDs |
| `aria-invalid` left set after a fix | Field is still announced as invalid | Remove the attribute when valid |
| Placeholder used as the label or hint | It disappears on input and has low contrast | Use a `label` and visible hint text |
| `role="alert"` on every message | Several messages interrupt each other | Link messages with `aria-describedby` and move focus instead |
| Generic text such as "Invalid" | User cannot tell what to change | Say what is wrong and what is allowed |
Exercise
A field has aria-describedby="email-hint" and your script writes the error into a new element email-error, but screen reader users do not hear it. What is missing, and what is the best fix?
Show answer
The control does not reference email-error. Change the attribute to aria-describedby="email-hint email-error", so both the hint and the error are read when the field gets focus. Also set aria-invalid="true" while the error is shown.
Exercise
Why does the submit handler call firstInvalid.focus() instead of giving every error message role="alert"?
Show answer
Moving focus to the first invalid field makes the screen reader read that field's label, invalid state, and linked message once, in a predictable order. Giving every message role="alert" makes several announcements compete and interrupt each other.