Pattern Accessibility Beginner
Accessible Forms
Each input is connected to a label, and ARIA attributes let screen readers announce validation errors, so the form works for screen reader users and keyboard users alike.
The problem
A screen reader user moves to an unlabeled input and has no idea what they’re supposed to enter. The placeholder says “Email,” but screen readers often don’t announce placeholders.
The pattern
Every input needs a <label> element with a for attribute that matches the input’s id. Clicking the label moves focus to the input, and screen readers announce the label when a user moves to the field.
Problem
I’ve tested forms where validation errors appeared as red text next to the input, and screen readers never announced them. Users would submit the form and get rejected without knowing why, then try again with the same data until they gave up.
Keyboard users have their own problems, such as a tab order that skips inputs or jumps around the form.
Solution
The required attribute tells screen readers that a field is required. An asterisk next to the label doesn’t help screen reader users, so it gets aria-hidden="true", and a short line at the top of the form tells sighted users what the asterisk means. If you show your own error messages, adding novalidate to the <form> disables the browser’s built-in validation bubbles, while the fields keep their required attribute for screen readers.
If validation fails, red text isn’t enough, because screen reader users also need to hear the error. If an error message has role="alert", screen readers announce it right away. On the field itself, aria-invalid="true" marks it as invalid, and aria-describedby connects it to its error message. After a failed submit, focus should move to the first invalid field, so the user is in the right place to fix it and doesn’t have to search the form for the error.
Related inputs belong in a <fieldset> with a <legend>. Radio buttons for “Payment method” don’t make much sense one at a time, and the legend tells screen reader users what the group of buttons is for.
The order of the elements in the DOM should match the order they appear on screen. If CSS moves things around, the tab order still follows the DOM, so focus can jump around the page as keyboard users press Tab.
Example
The Problem’s email field looks like this. The placeholder is its only label, and the error is a red <span> that nothing connects to the input.
<input type="email" placeholder="Email" />
<span class="red">Invalid email</span> <label for="email">Email address</label>
<input id="email" type="email" aria-describedby="email-error" aria-invalid="true" />
<div id="email-error" role="alert">Please enter a valid email address</div> The “after” field is shown as it looks once validation has failed. The full form below is shown before the user has typed anything, so the fields have no aria-invalid attribute and the error containers are empty.
<form novalidate>
<p>Fields marked * are required.</p>
<label for="email">Email address <span aria-hidden="true">*</span></label>
<input id="email" type="email" aria-describedby="email-hint email-error" required />
<div id="email-hint">We'll never share your email</div>
<!-- Empty until validation fails -->
<div id="email-error" role="alert"></div>
<label for="username">Username <span aria-hidden="true">*</span></label>
<input id="username" type="text" aria-describedby="username-error" required />
<div id="username-error" role="alert"></div>
<fieldset>
<legend>Newsletter frequency</legend>
<label><input type="radio" name="frequency" value="daily" /> Daily</label>
<label><input type="radio" name="frequency" value="weekly" checked /> Weekly</label>
<label><input type="radio" name="frequency" value="monthly" /> Monthly</label>
</fieldset>
<button type="submit">Create account</button>
<!-- Announces a successful submit -->
<div id="form-status" role="status"></div>
</form>
Validation on Blur and on Submit
The script below checks a field when the user leaves it, and checks both fields again on submit. After each failed check, the script sets aria-invalid="true" and puts the message into the field’s role="alert" container, so screen readers announce it as soon as it appears. If the submit fails, focus moves to the first invalid field, where the screen reader reads out the label and the error together. If it passes, the script puts the success message into the role="status" region, and screen readers announce it.
const checks = {
email: (value) =>
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) ? '' : 'Please enter a valid email address',
username: (value) => (value.trim() ? '' : 'Please enter a username'),
};
function validate(input) {
const message = checks[input.id](input.value);
input.setAttribute('aria-invalid', String(message !== ''));
document.getElementById(`${input.id}-error`).textContent = message;
return message === '';
}
const form = document.querySelector('form');
const fields = Object.keys(checks).map((id) => document.getElementById(id));
fields.forEach((input) => input.addEventListener('blur', () => validate(input)));
form.addEventListener('submit', (event) => {
event.preventDefault();
const invalid = fields.filter((input) => !validate(input));
if (invalid.length > 0) {
invalid[0].focus(); // first field that needs fixing
return;
}
document.getElementById('form-status').textContent =
'Account created successfully. Redirecting...';
setTimeout(() => { window.location.href = '/dashboard'; }, 2000);
});
Multiple Description References
One input can reference several descriptions, such as a hint, its requirements, and an error message.
<label for="password">Password</label>
<input
id="password"
type="password"
aria-describedby="password-hint password-requirements password-error"
/>
<div id="password-hint">Choose a strong password</div>
<div id="password-requirements">At least 15 characters. Spaces are allowed.</div>
<div id="password-error" role="alert"></div>
Benefits
- Screen reader users know what to enter, because each field’s label tells them what it’s for, and error messages are announced as well as displayed.
- More people might finish filling in your form, because more of them are able to use it.
- WCAG requires labels and clear error messages, so adding them is part of meeting WCAG.
- Clear labels and immediate feedback also make the form easier to use for people who don’t use a screen reader.
Tradeoffs
- Your HTML gets longer, because the IDs and
aria-describedbyreferences are extra markup to maintain. - Incorrect ARIA can be worse than none at all. If an
aria-describedbyreferences an ID that doesn’t exist, screen readers have nothing to announce, so you should test your markup. - Automated checkers only catch the obvious issues. NVDA, JAWS, and VoiceOver all behave differently, so you still need to test with real screen readers.
- Some CSS frameworks are built around HTML structures that don’t match accessible form markup, so their styles might not work with your markup.
- Too many live region announcements can overwhelm users. If each keystroke triggers an announcement, the form becomes harder to use with a screen reader.
- Some JavaScript frameworks generate dynamic IDs, which can break the connection between a label and its input.
- If you use both
aria-requiredand the HTMLrequiredattribute, screen readers can announce the field as required twice.
Summary
An accessible form needs a label connected to each input, and clear error messages. ARIA attributes let screen readers announce errors that appear during validation, focus should move to the first invalid field after a failed submit, and a logical tab order makes the form usable without a mouse. The extra markup helps you meet WCAG, and the clearer labels and errors help everyone who fills in the form.
See also
- ARIA Roles and Attributes — Accessibility
- Semantic HTML — Fundamentals
- Focus Management — Accessibility
- Creating Accessible Forms - W3C
- Form Validation - MDN
- ARIA Form Properties - MDN