Design and frontend · Intermediate · 24 min
How to Build Accessible HTML Forms
By Padding · Updated 15 Nov 2026
Modern browsers · WCAG 2.2 · checked in Chromium 159
You will build a contact form that works with keyboards and screen readers, with real labels, grouped radio buttons, hints tied to their fields, autocomplete values, and an error summary that takes focus and links to each problem, checking the result against specific WCAG 2.2 criteria.
On this page
A form is where a website asks something of a person, and it is where inaccessible pages fail people most. A field with no label is just a rectangle to a screen reader user. An error shown only in red does not reach someone who cannot see red. A form that cannot be completed with the keyboard cannot be completed at all by people who cannot use a mouse.
Most of the fixes come from using HTML as it was designed, with a few small additions of your own. This tutorial builds a contact form step by step and ties each decision to a numbered success criterion in the Web Content Accessibility Guidelines (WCAG) 2.2, so you know what you are meeting and can say so. It does not claim that following it makes a form accessible to everyone. Test with real people and real assistive technology too.
Step 1 · Start with labels and the right input types
Every control needs a visible label that is programmatically connected to it. A <label> with a for attribute that matches the input's id does both: clicking the label focuses the field, and the label text becomes the field's accessible name, which a screen reader reads when focus lands on it. This satisfies WCAG 1.3.1 Info and Relationships, 4.1.2 Name, Role, Value, and 3.3.2 Labels or Instructions. Hint text shown inside a field is not a label: it vanishes when the user types and is often too faint to read.
Create the page. The form uses the right type for each field, so phones show a suitable keyboard and browsers can check the value, and the autocomplete attribute names what each field is for. That last attribute lets browsers and password managers fill the form, which WCAG 1.3.5 Identify Input Purpose asks for on fields about the user:
mkdir -p ~/form-demo
cd ~/form-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Contact us</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Contact us</h1>
<p>All fields are required.</p>
<form id="signup" novalidate>
<div id="error-summary" class="summary" tabindex="-1" role="group" aria-labelledby="error-summary-title" hidden>
<h2 id="error-summary-title">There is a problem</h2>
<ul id="error-list"></ul>
</div>
<div class="field">
<label for="name">Full name</label>
<input id="name" name="name" type="text" autocomplete="name" required>
</div>
<div class="field">
<label for="email">Email address</label>
<p id="email-hint" class="hint">We only use it to reply to you.</p>
<input id="email" name="email" type="email" autocomplete="email" required aria-describedby="email-hint">
</div>
<div class="field">
<label for="password">Password</label>
<p id="password-hint" class="hint">At least 12 characters. You can paste from a password manager.</p>
<input id="password" name="password" type="password" autocomplete="new-password" minlength="12" required aria-describedby="password-hint">
</div>
<fieldset>
<legend>How should we reply?</legend>
<label class="choice"><input type="radio" name="reply" value="email" checked> By email</label>
<label class="choice"><input type="radio" name="reply" value="phone"> By phone</label>
</fieldset>
<div class="field">
<label for="message">Message</label>
<textarea id="message" name="message" rows="4" required></textarea>
</div>
<div class="field">
<label class="choice"><input type="checkbox" id="terms" name="terms" required> I agree to the <a href="/terms">terms</a></label>
</div>
<button type="submit">Send</button>
<p id="status" role="status"></p>
</form>
</main>
<script src="form.js"></script>
</body>
</html>
HTMLHere is why each choice matters:
type="email"andtype="password"give the right on-screen keyboard and let the browser check the value. A password field also hides what is typed.autocomplete="name","email"and"new-password"are values from the HTML specification's autofill list. Use"current-password"on a login form, and"one-time-code"for a code sent by text message.- The radio buttons sit in a
<fieldset>with a<legend>. The legend is read as the group's name along with each radio's label, so a screen reader user typically hears something like "How should we reply, group" and then "By email, radio button, selected". The exact wording differs between screen readers. - The hints are paragraphs connected to their inputs with
aria-describedby, so the hint is read after the field's name. Keep the label short and put the extra explanation in the hint. novalidateon the form switches off the browser's own pop-up messages, because you will write clearer ones. Therequiredandminlengthattributes stay, since you will use them.- The password field has no script that blocks pasting. WCAG 3.3.8 Accessible Authentication (Minimum) means people must be able to use a password manager or paste. Blocking it breaks that.
Check it worked
The next step adds the styles. For now, open index.html in a browser and press Tab repeatedly. Focus moves through the name, email, password, the radio group, the message, the checkbox, the link and the button, in the order they appear on the page, which satisfies WCAG 2.4.3 Focus Order. Click the words "Email address": the input receives focus. Hold on to the habit of tabbing through every form you build.
Step 2 · Style it so it is visible and easy to hit
Two requirements affect the CSS. Focus must be clearly visible, and controls must be large enough to hit. WCAG 2.2 criterion 2.5.8 Target Size (Minimum) asks for pointer targets of at least 24 by 24 CSS pixels. This sheet goes well beyond that. The code also keeps the browser's focus ring, restyled to be more visible, instead of removing it:
cat > style.css <<'CSS'
* { box-sizing: border-box; }
body { margin: 0; font: 1rem/1.6 system-ui, sans-serif; color: #1b1f24; background: #fff; }
main { max-width: 36rem; margin: 0 auto; padding: 1rem; }
.field { margin-bottom: 1.25rem; }
label { display: block; font-weight: 600; margin-bottom: 0.25rem; }
.choice { display: flex; align-items: center; gap: 0.5rem; font-weight: 400; min-height: 2.75rem; }
.hint { margin: 0 0 0.25rem; color: #4a5560; font-size: 0.9rem; }
input[type="text"], input[type="email"], input[type="password"], textarea {
width: 100%; min-height: 2.75rem; padding: 0.5rem; font: inherit;
border: 2px solid #5b6672; border-radius: 0.25rem;
}
input[type="radio"], input[type="checkbox"] { width: 1.5rem; height: 1.5rem; }
fieldset { border: 0; padding: 0; margin: 0 0 1.25rem; }
legend { font-weight: 600; padding: 0; }
button { min-height: 2.75rem; padding: 0.5rem 1.25rem; font: inherit; font-weight: 600;
color: #fff; background: #0b5cad; border: 0; border-radius: 0.25rem; cursor: pointer; }
:focus-visible { outline: 3px solid #0b5cad; outline-offset: 2px; }
a { color: #0b5cad; }
[aria-invalid="true"] { border-color: #a8071a; }
.error { margin: 0.25rem 0 0; color: #a8071a; font-weight: 600; }
.summary { border: 3px solid #a8071a; padding: 1rem; margin-bottom: 1.5rem; }
.summary h2 { margin: 0 0 0.5rem; font-size: 1.1rem; color: #a8071a; }
.summary a { color: #a8071a; font-weight: 600; }
#status { font-weight: 600; }
CSSNotes on these choices. Borders on the inputs are a darker grey that stands out from white, because WCAG 1.4.11 Non-text Contrast asks for 3:1 between a control's boundary and its background. The error colour #a8071a on white has a contrast of more than 7:1. Error borders are accompanied by text, so colour is never the only signal (WCAG 1.4.1 Use of Color). :focus-visible shows the ring for keyboard users, and for mouse clicks only where the browser decides it helps.
Check it worked
Reload. The fields are full width with clear borders, and each text field and the button is at least 44 pixels tall. Press Tab: a blue ring appears around each control as it receives focus.
Step 3 · Show errors that people can find and fix
Browsers' default validation bubbles disappear, are inconsistent, and are hard to reach with assistive technology. A reliable pattern has three parts. An error message sits next to each bad field, in text, tied to the field with aria-describedby, and the field is marked aria-invalid="true". An error summary at the top of the form lists every problem, each as a link to its field. And when the user submits, focus moves to the summary so everyone, including screen reader users, sees that something went wrong. This covers WCAG 3.3.1 Error Identification and 3.3.3 Error Suggestion, because each message says what is wrong and how to fix it.
Create form.js. It uses the browser's Constraint Validation API: checkValidity() tells you whether a field passes its required, type and minlength rules, and the field's validity object says which rule failed:
cat > form.js <<'JS'
const form = document.getElementById("signup");
const summary = document.getElementById("error-summary");
const list = document.getElementById("error-list");
const status = document.getElementById("status");
const messages = {
name: { valueMissing: "Enter your full name." },
email: {
valueMissing: "Enter your email address.",
typeMismatch: "Enter an email address in the format name@example.com.",
},
password: {
valueMissing: "Enter a password.",
tooShort: "Use at least 12 characters for your password.",
},
message: { valueMissing: "Enter a message." },
terms: { valueMissing: "Tick the box to agree to the terms." },
};
function messageFor(field) {
const known = messages[field.id] ?? {};
for (const reason of ["valueMissing", "typeMismatch", "tooShort"]) {
if (field.validity[reason] && known[reason]) return known[reason];
}
return field.validationMessage;
}
function clearErrors() {
summary.hidden = true;
list.replaceChildren();
for (const message of form.querySelectorAll(".error")) message.remove();
for (const field of form.querySelectorAll("[aria-invalid]")) {
field.removeAttribute("aria-invalid");
if (field.dataset.hint) field.setAttribute("aria-describedby", field.dataset.hint);
else field.removeAttribute("aria-describedby");
}
}
function showErrors(fields) {
for (const field of fields) {
const errorId = `${field.id}-error`;
const text = messageFor(field);
const paragraph = document.createElement("p");
paragraph.id = errorId;
paragraph.className = "error";
paragraph.textContent = `Error: ${text}`;
field.closest(".field").append(paragraph);
field.dataset.hint = field.getAttribute("aria-describedby") ?? "";
field.setAttribute("aria-invalid", "true");
field.setAttribute("aria-describedby", [field.dataset.hint, errorId].filter(Boolean).join(" "));
const item = document.createElement("li");
const link = document.createElement("a");
link.href = `#${field.id}`;
link.textContent = text;
item.append(link);
list.append(item);
}
summary.hidden = false;
summary.focus();
}
list.addEventListener("click", (event) => {
const link = event.target.closest("a");
if (!link) return;
event.preventDefault();
document.getElementById(link.hash.slice(1)).focus();
});
form.addEventListener("submit", (event) => {
event.preventDefault();
clearErrors();
status.textContent = "";
const invalid = [...form.elements].filter((field) => field.willValidate && !field.checkValidity());
if (invalid.length > 0) {
showErrors(invalid);
return;
}
// A real form would send the data here, or call form.submit().
status.textContent = "Thanks, we have your message.";
form.reset();
});
JSHow it works. On submit the script clears any old errors, then checks each field. For every failing field, it adds a message after the field, sets aria-invalid, and appends the error's id to the field's aria-describedby, next to the hint, so the screen reader reads the name, then the hint, then the error. The summary link for each problem moves focus to its field when clicked, because a plain link to #email scrolls but does not always move keyboard focus. The aria-describedby value that existed before the error is kept in data-hint so that the next submit can restore it.
The success message goes in <p id="status" role="status">. An element with role="status" is a live region: when its text changes, assistive technology announces it without moving focus. That is how WCAG 4.1.3 Status Messages is met.
Check it worked
Reload, leave every field empty and press the Send button. A box titled "There is a problem" appears at the top with five links. Keyboard focus is on the box, and each field shows a red "Error: ..." line below it and a red border. Now type abc in the email field and a short password, and send again. The messages change to one asking for an email address in the right format and "Use at least 12 characters for your password." Fill the form correctly and send: the errors disappear and "Thanks, we have your message." appears.
Troubleshooting
If nothing happens when you submit, open the browser console (F12) and look for a red error: a typo in an id is the usual cause, since the script looks fields up by id. If the summary appears but the links do nothing, check that the list.addEventListener("click", ...) block is present. If the page reloads on submit, the script did not load: check that form.js is in the same folder and the <script> tag is at the end of index.html.
Step 4 · Check it the way a user would
Automated tools find only a part of the problems, so check by hand. These checks take five minutes:
- Unplug the mouse. Complete the form with only Tab, Shift+Tab, Space (checkboxes and radios), the arrow keys (within a radio group) and Enter. Focus must always be visible, and nothing may trap it.
- Zoom the browser to 200 percent and then make the window 320 pixels wide. Nothing should need sideways scrolling, and nothing should be cut off.
- Open the accessibility tree. In Chrome and Edge, DevTools has an Accessibility pane in the Elements panel, and Firefox has an Accessibility panel. Click each field and read its computed name and description. The name must be the label text and the description must be the hint, then the error. This is the information a screen reader receives.
- Switch on a screen reader and listen once. VoiceOver is built into macOS and iOS, TalkBack into Android, NVDA is free for Windows, and Narrator is built into Windows. Fields should be announced as, for example, "Email address, edit text, we only use it to reply to you."
- Run an automated checker such as the axe DevTools extension or Lighthouse's accessibility audit, and fix what it finds. Treat a clean report as the start of testing, since these tools cannot judge whether a label makes sense.
Errors need care beyond this form too. Say what went wrong in plain words (such as the format an email address needs) and not codes. Keep what the user typed when an error appears, except for passwords. WCAG 3.3.7 Redundant Entry, new in 2.2, also asks you not to make people enter the same information twice in one process.
Step 5 · Clean up
Remove the demo folder:
cd ~
rm -rf ~/form-demoNext steps
- Make the page respect the reader's light or dark setting: add dark mode with CSS variables.
- Lay the form out in a grid on wide screens: build page layouts with CSS Grid.
- Read the criteria themselves: the WCAG 2.2 specification at w3.org/TR/WCAG22 and the "How to Meet WCAG" quick reference from the W3C.
Related tutorials
- How to Build Page Layouts with CSS GridYou will build a page with a header, sidebar, main area and footer using named grid areas, fill it with a grid of cards that adds and removes columns by itself, make one card span two columns, and change the layout for narrow screens.
- How to Add Dark Mode to a Website with CSS VariablesYou will define your colours once as CSS custom properties, switch them with light-dark() and the user's system setting, add a toggle button that remembers the choice without a flash on reload, and check the text contrast of both themes with a short script.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials