Accessible Forms: Build Better Web Experiences
Learn how to build accessible forms with semantic HTML, ARIA, validation, focus management, and Rails form_with examples.
By Jean Emmanuel Cadet • 36 min read
Forms are where a website stops being a brochure and starts doing real work. Signing up, checking out, booking an appointment, contacting support: almost every meaningful action on the web passes through a form. That makes forms the place where an accessibility barrier does the most damage.
Picture a few common failures. A field has only a placeholder, so a screen reader user hears "edit text" with no clue what to type. An error appears as a red border and nothing else, so a person with color blindness never sees it. A custom dropdown ignores the Tab key, so someone who cannot use a mouse is stuck on step two of checkout. None of these users failed the form. The form failed them.
The good news is that accessible forms are mostly built from ordinary, well-chosen HTML. Clear labels, helpful instructions, specific error messages and a sensible focus order do not only help people with disabilities. They help someone filling in a form on a phone in bright sunlight, a power user who never touches the mouse, and a tired person on their fifth form of the day. Accessibility improves usability for everyone.
This guide is for web developers, frontend developers and Ruby on Rails developers. We start with the fundamentals, move through validation, focus management and dynamic behavior, then build a complete accessible Rails form and test it.
What Is Form Accessibility?
Web accessibility means designing and building websites so people with a wide range of abilities can perceive, understand, navigate and interact with them. Inclusive design goes a step further: it considers the full range of human diversity (disability, age, language, device, situation) from the start instead of patching problems later.
Form accessibility applies those ideas to one task: making sure everyone can understand what a form asks for, fill it in, submit it, and recover when something goes wrong.
The shared yardstick is the Web Content Accessibility Guidelines (WCAG), published by the W3C. WCAG 2.2 is the current version. It is organized around four principles, often abbreviated POUR:
- Perceivable: information can be perceived by sight, hearing or touch (for example, labels and error text, not only color).
- Operable: controls work with a keyboard, voice input and other devices.
- Understandable: instructions and errors are clear and behavior is predictable.
- Robust: markup works with browsers and assistive technologies.
Each guideline has success criteria (SC) at level A, AA or AAA. Most laws and procurement policies that reference WCAG target level AA, and that is the target used throughout this article. I will cite specific success criteria where they help, and I will separate requirements (WCAG success criteria) from recommendations (good practice beyond the minimum).
Why Accessible Forms Matter
Different people interact with the same form in very different ways. Here are the main groups to keep in mind.
- Screen reader users hear the page read aloud (or read it on a braille display). They rely on programmatic labels, descriptions and error associations, because they cannot see the visual layout.
- Keyboard users navigate with Tab, Shift+Tab, arrow keys, Space and Enter. This includes people with motor disabilities, people with repetitive strain injuries, and many experienced developers.
- Voice input users speak commands such as "click Email". This works only when the visible label matches the control's accessible name (WCAG SC 2.5.3, Label in Name).
- Screen magnification users see a small part of the page at a time. If a label sits far from its input, or an error appears off-screen, they may never find it.
- People with cognitive or learning disabilities benefit from plain language, consistent patterns, visible instructions and autocomplete that reduces memory load.
- Everyone, sometimes. A broken trackpad, a noisy train, one free hand or a small phone screen creates the same barriers temporarily.
There is also a practical business reason. Accessible forms tend to have fewer abandoned submissions and fewer support tickets, because people understand what to do and can fix their mistakes without help.
Understanding Semantic HTML
Semantic HTML means choosing elements for their meaning, not their appearance. Native form elements come with a role (what the control is), a name (what it is called), a state (checked, required, invalid), keyboard behavior and focus handling, all for free. This leads to the most important rule of accessible forms: use native HTML whenever it does the job, and add ARIA only when it cannot.
Compare these two approaches to a newsletter signup.
<!-- Inaccessible: no real controls, no label association, not keyboard operable -->
<div class="field">
<div class="input-label">Email</div>
<div class="fake-input" contenteditable="true"></div>
<div class="btn" onclick="submitForm()">Subscribe</div>
</div>
<!-- Accessible: native elements provide role, name, keyboard and submit behavior -->
<form action="/newsletter" method="post">
<label for="email">Email</label>
<input type="email" id="email" name="email" autocomplete="email" required>
<button type="submit">Subscribe</button>
</form>
The first version looks fine to a mouse user and is nearly unusable otherwise. The second is shorter and works with every input method.
Here is what each native element contributes:
form: groups controls and defines submission. If you give it an accessible name (for example witharia-labelledbypointing to a heading), assistive technologies expose it as a form landmark, which helps navigation.label: gives a control its visible, programmatic name.input: thetypeattribute matters.email,tel,password,numberanddatetrigger the right mobile keyboards and built-in validation.textarea: multi-line text. Enter adds a new line instead of submitting.select: a native dropdown with built-in keyboard and screen reader support that is very hard to replicate with custom markup.button: always settype. Inside a form a button defaults tosubmit, so usetype="button"for actions that should not submit.fieldsetandlegend: group related controls and give the group a name, covered in detail later.
Labels and Form Controls
Every form control needs an accessible name: the text assistive technologies announce to identify it. For form fields, the best source of that name is a visible label.
Connect a label to a control with the for attribute, which must match the control's id:
<label for="full-name">Full name</label>
<input type="text" id="full-name" name="full_name" autocomplete="name">
You can also wrap the input inside the label (implicit association), but explicit for and id pairing is more flexible for styling and is the pattern Rails generates. IDs must be unique on the page. A side benefit: clicking the label focuses the input, which enlarges the click target for everyone.
Placeholders Are Not Labels
A placeholder is the hint text shown inside an empty input. It is tempting to use it instead of a label, because it saves space. Do not do it:
<!-- Inaccessible: the placeholder disappears as soon as the user types -->
<input type="email" name="email" placeholder="Email address">
Placeholders vanish when the user starts typing, so people lose the prompt exactly when they need to double-check it. Browser default placeholder colors often fail contrast requirements. Placeholders can be mistaken for a prefilled value, and support for them as an accessible name is a fallback, not a guarantee. Use a persistent label and, if you want, a short example in the placeholder or, better, in help text.
A Note on aria-label
aria-label supplies an accessible name that is not visible. It is not a replacement for a visible label. Sighted users, voice input users and people with cognitive disabilities all benefit from seeing the label. If you must name a control without visible text (for example a search field beside a button that clearly says "Search"), keep the accessible name consistent with any visible text (SC 2.5.3).
Instructions and Help Text
Labels say what a field is. Instructions say how to fill it in correctly. WCAG SC 3.3.2 (Labels or Instructions, level A) requires labels or instructions whenever content requires user input.
Good help text covers the expected format ("Use the format DD/MM/YYYY"), constraints ("At least 12 characters") and why you are asking, when it is not obvious. Place it next to the field, in visible text, before the user starts typing.
Associate help text with its control using aria-describedby. The attribute points to one or more element IDs, and assistive technologies announce that text as the control's accessible description, usually after the name and role.
<label for="password">Password</label>
<p id="password-hint" class="field-hint">Use at least 12 characters. Spaces are allowed.</p>
<input
type="password"
id="password"
name="password"
autocomplete="new-password"
minlength="12"
required
aria-describedby="password-hint"
>
You can reference several IDs, separated by spaces: aria-describedby="password-hint password-error". Avoid relying on the title attribute or hover tooltips for essential instructions, because touch and keyboard users often cannot reach them.
Also set autocomplete values on fields that collect personal data (name, email, address, one-time codes). That satisfies WCAG SC 1.3.5 (Identify Input Purpose, level AA) and saves users effort. For authentication, WCAG 2.2 SC 3.3.8 (Accessible Authentication, level AA) means you should not block password managers or pasting into password fields.
Required Fields and Optional Fields
Users need to know which fields they must complete. Mark this in three ways that work together:
- Use the native
requiredattribute, so assistive technologies announce the required state. - State the convention in visible text near the top of the form.
- Never rely on color alone (SC 1.4.1, Use of Color, level A).
A red asterisk is the classic anti-pattern. It can be ignored by screen readers, it may be invisible to users who cannot distinguish the color, and it means nothing unless explained. If you use asterisks, explain them in text and make sure the required attribute is present. A plainer pattern is usually better: say that all fields are required unless marked optional, and label the optional ones in words.
<p>All fields are required unless marked optional.</p>
<label for="company">Company <span class="field-flag">(optional)</span></label>
<input type="text" id="company" name="company" autocomplete="organization">
Choose whichever group is smaller (required or optional) to mark, and be consistent across the whole site.
aria-required="true" duplicates what required already conveys on native controls, so skip it unless you build a custom widget with an ARIA role.
For styling, prefer the :user-invalid pseudo-class over :invalid. The older :invalid matches empty required fields immediately on page load, which shows errors before the user has done anything. :user-invalid only matches after the user has interacted, and it is now supported in current evergreen browsers.
Accessible Form Validation
Validation checks that submitted data is acceptable. There are two layers, and you need both.
- Client-side validation runs in the browser. It gives fast feedback, but it can be bypassed or disabled, so it is a convenience.
- Server-side validation runs on your server. It is the authority, and it must work without JavaScript.
HTML gives you client-side validation for free through attributes such as required, type="email", minlength, maxlength, min, max and pattern. These use the browser's Constraint Validation API. The default bubbles are better than nothing, but their wording and behavior vary between browsers and may not always be announced consistently. Many teams add novalidate to the form and handle messages themselves, so errors look the same everywhere and can be associated with fields. If you do that, the server must validate everything, because novalidate turns off the browser's built-in checks.
Here is an optional Stimulus controller that enhances a novalidate form with accessible client-side errors:
// app/javascript/controllers/validate_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["field"]
submit(event) {
const invalid = this.fieldTargets.filter((field) => !field.checkValidity())
if (invalid.length === 0) return
event.preventDefault()
invalid.forEach((field) => this.showError(field))
invalid[0].focus()
}
clear(event) {
const field = event.target
if (field.getAttribute("aria-invalid") !== "true" || !field.checkValidity()) return
const errorId = `${field.id}_error`
field.removeAttribute("aria-invalid")
document.getElementById(errorId)?.remove()
const ids = this.describedBy(field).filter((id) => id !== errorId)
if (ids.length > 0) {
field.setAttribute("aria-describedby", ids.join(" "))
} else {
field.removeAttribute("aria-describedby")
}
}
showError(field) {
const errorId = `${field.id}_error`
let error = document.getElementById(errorId)
if (!error) {
error = document.createElement("p")
error.id = errorId
error.className = "field-error"
field.insertAdjacentElement("beforebegin", error)
}
error.textContent = `Error: ${field.validationMessage}`
field.setAttribute("aria-invalid", "true")
const ids = this.describedBy(field)
if (!ids.includes(errorId)) ids.push(errorId)
field.setAttribute("aria-describedby", ids.join(" "))
}
describedBy(field) {
return (field.getAttribute("aria-describedby") || "").split(" ").filter(Boolean)
}
}
Use it by adding data-controller="validate" and data-action="submit->validate#submit input->validate#clear" to the form, and data-validate-target="field" to each control. The browser's validationMessage can be generic, so for specific wording call setCustomValidity() with your own text.
What Good Validation Looks Like
- Validate on submit, and after a user leaves a field. Do not show an error while someone is still typing their email address.
- Be specific and actionable. Say what is wrong and how to fix it (SC 3.3.1 Error Identification, level A; SC 3.3.3 Error Suggestion, level AA).
- Protect important submissions. For legal, financial or data-changing actions, let users review, correct or reverse them (SC 3.3.4, level AA).
- Do not make users re-enter information you already have in the same session (SC 3.3.7 Redundant Entry, level A, new in WCAG 2.2).
If you need validation beyond presence and format, a well-organized custom validator keeps the messages consistent. See custom validators in Rails for patterns you can reuse.
Error Messages and Error Identification
When a field is invalid, the user needs to know three things: that an error exists, which field has it, and how to fix it. Color alone cannot carry any of that.
A reliable pattern has four parts:
- Visible error text near the field, starting with the word "Error" so it does not depend on color.
aria-describedbyon the control pointing to the error element.aria-invalid="true"on the control.- A page-level error summary with links to each problem field (covered in the Rails section).
<label for="email">Email</label>
<p id="email-hint" class="field-hint">We only use this to reply to you.</p>
<p id="email-error" class="field-error">
<span class="field-error__prefix">Error:</span>
Enter an email address like [email protected]
</p>
<input
type="email"
id="email"
name="email"
value="maria.example.com"
autocomplete="email"
required
aria-invalid="true"
aria-describedby="email-hint email-error"
>
aria-invalid="true" is a state. It tells assistive technologies that the current value is not acceptable. Set it only when a field is actually invalid, and remove it when the problem is fixed. Do not add aria-invalid="false" to every field on page load. Do not put aria-invalid on a native fieldset, since that role does not support it (describe the group's error with aria-describedby instead).
Write messages as if you were helping someone in person:
Unhelpful | Helpful |
|---|---|
Invalid input | Enter an email address like [email protected] |
Required | Enter your full name |
Error in field | Choose a topic from the list |
Password too weak | Use at least 12 characters |
Avoid blaming the user, and avoid error codes that only developers understand.
Keyboard Accessibility
Many people never use a mouse, and a form that cannot be completed by keyboard fails WCAG SC 2.1.1 (Keyboard, level A). Native controls handle this well:
- Tab and Shift+Tab move to the next and previous focusable control.
- Arrow keys move between radio buttons in a group (the group is a single tab stop) and change the value of a
select. Exact behavior for opening aselectvaries by browser. - Space toggles a checkbox, selects the focused radio button and activates a button.
- Enter activates a button and submits the form from most single-line inputs. In a
textareait adds a new line.
Focus Order
Focus follows the DOM order, and that order should match the visual reading order (SC 2.4.3, Focus Order, level A). Avoid positive tabindex values such as tabindex="3", which create confusing, hard-to-maintain tab sequences. Be careful with CSS that visually reorders content (order in flexbox or grid), because it separates what users see from the order focus moves in.
Visible Focus
Keyboard users need to see where they are (SC 2.4.7, Focus Visible, level AA). Never write outline: none without a replacement.
:focus-visible {
outline: 3px solid #0b57d0;
outline-offset: 2px;
}
html {
scroll-padding-top: 5rem; /* keeps focused fields clear of a sticky header */
}WCAG 2.2 adds SC 2.4.11 (Focus Not Obscured, Minimum, level AA): a focused control must not be entirely hidden by sticky headers or cookie banners. The scroll-padding-top rule above helps with that.
Avoiding Keyboard Traps
A keyboard trap is a place where focus enters but cannot leave (SC 2.1.2, No Keyboard Trap, level A). The usual culprits are custom date pickers, rich text editors and modals without an Escape or close control. Test every widget by tabbing in and out.
Screen Reader Accessibility
Screen readers build their understanding of a control from four pieces of information:
- Name: from the label (for example, "Email").
- Role: from the element type (for example, "edit text", "checkbox", "combo box").
- State and value: required, invalid, checked, expanded, the current text.
- Description: from
aria-describedby(the hint and the error).
A well-built field might be announced as something like: "Email, edit text, required, invalid entry, We only use this to reply to you. Error: Enter an email address like [email protected]". The wording and order differ between screen readers, browsers and settings, so treat that as an illustration, not a specification.
Groups matter too. When focus enters a radio button inside a fieldset, many screen readers announce the legend text together with the radio label, so users hear the question and the answer. Headings and landmarks help users move around longer forms.
Screen readers often have separate modes for reading content and for interacting with form controls, and they switch automatically as users move through a page. That works smoothly when you use native controls. It is one more reason to avoid custom widgets that pretend to be inputs.
Accessible Grouped Controls
Use fieldset and legend whenever several controls answer one question, most commonly radio button groups, checkbox groups and multi-part answers such as a date of birth or an address block.
<fieldset>
<legend>How should we contact you?</legend>
<div class="choice">
<input type="radio" id="contact-email" name="contact_method" value="email" required>
<label for="contact-email">Email</label>
</div>
<div class="choice">
<input type="radio" id="contact-phone" name="contact_method" value="phone" required>
<label for="contact-phone">Phone</label>
</div>
</fieldset>
The legend is the group's accessible name, and each label names its own option. Keep legends short and specific. Do not wrap an entire long form in one fieldset, and do not nest fieldsets deeply. A single standalone checkbox (such as "I agree to the terms") does not need a fieldset, because its label is enough.
Browsers give fieldsets default borders and a minimum width that can break layouts. Reset those styles in CSS instead of replacing the element with a div. Use role="group" with aria-labelledby only when a fieldset is truly impractical.
Accessible Buttons and Actions
A button label should describe the result of pressing it. "Create account", "Send message" and "Save address" are clear. "Submit", "Go", "OK" and "Click here" are ambiguous, especially when screen reader users list all the buttons on a page.
Some practical rules:
- Use a real
buttonelement. Use a link (a) for navigation and a button for actions. - Set
type="submit"for the main action andtype="button"for anything that should not submit the form. - Icon-only buttons need an accessible name, and visible text is still preferable.
- Avoid a "Reset" button next to "Submit", since accidental clicks erase user input.
- Ask for confirmation, or offer an undo, for destructive actions.
Loading States
When a form takes time to submit, users need feedback and protection from duplicate submissions. Change the button text (for example to "Sending...") and consider announcing progress in a live region. Be careful with the disabled attribute, because a disabled button cannot hold focus and, in some browsers, keyboard focus can be lost to the page body. In Rails with Turbo, data-turbo-submits-with swaps the button text during submission, and Turbo also marks the form with aria-busy while it submits. Focus management after the response, covered next, makes sure users land somewhere sensible.
Focus Management
Focus management means deliberately deciding where keyboard and screen reader focus goes when the page changes. When content updates and focus stays on something that has disappeared, users are lost. When focus jumps unexpectedly, users are disoriented. The rule of thumb is to move focus only when the user needs to be taken somewhere new, and to leave it alone otherwise.
Common situations:
- After a failed submission: move focus to the error summary heading (or to the first invalid field if there is no summary). Screen readers then announce the problem, and keyboard users can tab straight to the links.
- After a successful submission: move focus to a confirmation heading, or to the new page's main heading.
- After adding a field: move focus to the new control.
- After removing a field: move focus to a logical neighbor, such as the previous item or the "Add" button, never to the top of the page.
- During typing or inline validation: do not move focus at all.
To make a non-interactive element such as a heading focusable by script, give it tabindex="-1". That lets focus() work without putting the element in the normal tab order. A small reusable Stimulus controller handles the common case:
// app/javascript/controllers/focus_controller.js
import { Controller } from "@hotwired/stimulus"
// Moves focus to this element when it appears on the page.
export default class extends Controller {
connect() {
this.element.focus()
}
}
<h2 id="error-summary-title" tabindex="-1" data-controller="focus">
2 problems to fix
</h2>
When Turbo renders the failed form, the heading connects, the controller runs and focus moves. If you do not use Stimulus, the same effect takes one line: document.getElementById("error-summary-title").focus().
Accessible Dynamic Forms
Forms that change while the user interacts (conditional fields, repeatable groups, suggestions) need extra care, because screen reader users cannot see the change happen. The aim is to make every change either discoverable in the normal reading order or announced.
Conditional Fields
Reveal related fields directly after the control that triggers them, so they are next in the tab order. Use the hidden attribute to hide them, and disable hidden controls so they are not validated or submitted.
<div class="field" data-controller="reveal">
<div class="choice">
<input type="checkbox" id="phone_reply" name="contact_message[phone_reply]" value="1"
data-reveal-target="toggle" data-action="reveal#update">
<label for="phone_reply">Call me back</label>
</div>
<div data-reveal-target="panel" hidden>
<label for="phone">Phone number</label>
<p id="phone-hint" class="field-hint">Include your country code, for example +1 555 123 4567.</p>
<input type="tel" id="phone" name="contact_message[phone]" autocomplete="tel"
required aria-describedby="phone-hint">
</div>
</div>
// app/javascript/controllers/reveal_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["toggle", "panel"]
connect() {
this.update()
}
update() {
const open = this.toggleTarget.checked
this.panelTarget.hidden = !open
this.panelTarget.querySelectorAll("input, select, textarea").forEach((field) => {
field.disabled = !open
})
}
}
Both controls are native, so no ARIA is needed. If you instead use a button to show or hide a section, put aria-expanded on that button and aria-controls pointing to the section. aria-expanded is not valid on a checkbox.
Dynamically Added Inputs
When a user adds another item, move focus to the new field. Its label is announced, so no extra message is required.
<div data-controller="repeater">
<div data-repeater-target="list">
<div class="field">
<label for="attendee_1">Attendee 1 name</label>
<input type="text" id="attendee_1" name="registration[attendees][]" autocomplete="off">
</div>
</div>
<template data-repeater-target="template">
<div class="field">
<label for="attendee_INDEX">Attendee INDEX name</label>
<input type="text" id="attendee_INDEX" name="registration[attendees][]" autocomplete="off">
</div>
</template>
<button type="button" data-action="repeater#add">Add another attendee</button>
</div>
// app/javascript/controllers/repeater_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["list", "template"]
add() {
const index = this.listTarget.children.length + 1
const html = this.templateTarget.innerHTML.replaceAll("INDEX", index)
this.listTarget.insertAdjacentHTML("beforeend", html)
this.listTarget.querySelector(`#attendee_${index}`).focus()
}
}
Autocomplete Suggestions
For a simple list of suggestions, the native datalist element is the lowest-risk option:
<label for="country">Country</label>
<input type="text" id="country" name="country" list="country-options" autocomplete="country-name">
<datalist id="country-options">
<option value="Haiti"></option>
<option value="Canada"></option>
<option value="United States"></option>
</datalist>
Its styling is limited and assistive technology support varies, so test it. If you need richer suggestions, the ARIA combobox pattern requires an input with role="combobox", aria-autocomplete="list", aria-expanded and aria-controls pointing to a listbox, options with role="option", aria-activedescendant to track the highlighted option, and full keyboard support (arrows, Enter, Escape). That is a lot to get right, so prefer a well-tested library over writing your own.
Announcing Changes with Live Regions
A live region is an element whose content changes are announced without moving focus. Use role="status" (polite, waits for a pause) for non-urgent updates such as "Address saved", and reserve role="alert" (assertive, interrupts) for urgent problems. The region must already exist in the page before you change its text, or the update may not be announced.
<div id="form-status" role="status" class="visually-hidden"></div>
document.getElementById("form-status").textContent = "Address saved"This supports WCAG SC 4.1.3 (Status Messages, level AA). Do not wrap every inline error in role="alert" and avoid firing many announcements at once. Also, never submit or navigate automatically when a control changes, such as a select that jumps to a new page on selection (SC 3.2.2, On Input, level A).
Color Contrast and Visual Design
Visual design decides whether people with low vision, color blindness or aging eyes can use your form. These are the WCAG requirements that matter most for forms:
- Text contrast of at least 4.5:1 against its background (3:1 for large text), SC 1.4.3, level AA.
- Contrast of at least 3:1 for input borders, focus indicators and other UI component boundaries, SC 1.4.11 (Non-text Contrast), level AA.
- Color is never the only signal for errors, required fields or status, SC 1.4.1, level A.
- Target size of at least 24 by 24 CSS pixels for controls, with exceptions, SC 2.5.8 (Target Size, Minimum), level AA, new in WCAG 2.2.
- Content reflows at narrow widths (320 CSS pixels) and survives zoom to 200%, SC 1.4.4 and 1.4.10, level AA.
Recommendations (not strict requirements) that make forms noticeably easier to use: input text of at least 16px, generous line height, labels above inputs instead of beside them on small screens, and text that tolerates user-adjusted spacing (SC 1.4.12).
Here is a stylesheet that puts these ideas into practice:
:root {
--text: #1f1f1f;
--muted: #4a4a4a;
--border: #595959; /* about 7:1 on white */
--focus: #0b57d0; /* about 6.4:1 on white */
--error: #b00020; /* about 7.3:1 on white */
}
body {
font: 1rem/1.6 system-ui, sans-serif;
color: var(--text);
}
.field {
margin: 0 0 1.5rem;
}
fieldset.field {
border: 0;
padding: 0;
min-inline-size: 0;
}
label,
legend {
display: block;
margin: 0 0 0.25rem;
padding: 0;
font-weight: 600;
}
.field-hint {
margin: 0 0 0.5rem;
color: var(--muted);
}
input[type="text"],
input[type="email"],
input[type="password"],
input[type="tel"],
select,
textarea {
box-sizing: border-box;
inline-size: 100%;
max-inline-size: 32rem;
padding: 0.625rem 0.75rem;
font: inherit;
color: var(--text);
background: #fff;
border: 2px solid var(--border);
border-radius: 0.375rem;
}
.choice {
display: flex;
align-items: center;
gap: 0.75rem;
margin: 0 0 0.5rem;
}
.choice label {
margin: 0;
font-weight: 400;
}
input[type="radio"],
input[type="checkbox"] {
flex: none;
inline-size: 1.5rem;
block-size: 1.5rem;
margin: 0;
}
:focus-visible {
outline: 3px solid var(--focus);
outline-offset: 2px;
}
input[aria-invalid="true"],
select[aria-invalid="true"],
textarea[aria-invalid="true"] {
border-color: var(--error);
box-shadow: inset 0 0 0 1px var(--error);
}
.field-error {
margin: 0 0 0.5rem;
color: var(--error);
font-weight: 600;
}
.error-summary {
margin: 0 0 1.5rem;
padding: 1rem;
border: 4px solid var(--error);
}
.error-summary a {
color: var(--error);
text-decoration: underline;
}
.visually-hidden {
position: absolute;
inline-size: 1px;
block-size: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}Notice that the error state combines a red border, an inner shadow, bold error text and the word "Error:". Removing the red would still leave a clear error. Using outline for focus (instead of only box-shadow) also keeps the indicator visible in forced-colors modes such as Windows High Contrast.
Accessible Forms in Ruby on Rails
Rails form helpers are a great starting point because they generate valid, label-friendly HTML. But they only generate what you ask for. Rails will not write your label text, your instructions, your error messages or your focus logic. The markup is only accessible if you make it so, and you are responsible for checking the result.
Here is what each helper gives you and what remains your job:
Helper | Generates | Still up to you |
|---|---|---|
|
| A heading or name for the form, a decision on |
|
| Clear, specific label text |
|
|
|
|
| Same, with |
|
|
|
|
| Hint text, sensible |
|
| A blank prompt option, |
|
| A |
| Checkbox plus a hidden input | A label, and a |
A Small Helper for Descriptions and Invalid State
Rails 7 and later provide form.field_id, which accepts suffixes so you can build predictable IDs for hints and errors, for example form.field_id(:email, :hint). This small helper uses it to compute aria-describedby and aria-invalid:
# app/helpers/form_accessibility_helper.rb
module FormAccessibilityHelper
# Returns aria attributes for a field: linked hint and error IDs plus invalid state.
def field_aria(form, attribute, hint: false)
invalid = form.object.errors[attribute].any?
ids = []
ids << form.field_id(attribute, :hint) if hint
ids << form.field_id(attribute, :error) if invalid
{ describedby: ids.join(" ").presence, invalid: (invalid ? "true" : nil) }
end
end
Passing nil for an aria value makes Rails omit the attribute, so valid fields stay clean.
Taming field_error_proc
By default, Rails wraps any invalid field (and its label) in a div class="field_with_errors". That wrapper adds no accessibility value and can break flex or grid layouts. Since we mark fields explicitly with the helper above, we can leave the markup untouched:
# config/application.rb
module YourApp
class Application < Rails::Application
# Do not wrap invalid fields and labels in extra markup.
config.action_view.field_error_proc = proc { |html_tag, _instance| html_tag }
end
end
You could add aria-invalid inside this proc with string manipulation, but that is fragile because the proc also runs for labels. Explicit helper calls are easier to read and test.
Putting the Helpers Together
This sign-up form uses form_with, label, email_field and password_field, with a linked hint on the password:
<%# app/views/registrations/new.html.erb %>
<h1 id="signup-title">Create your account</h1>
<%= render "shared/error_summary", model: @user %>
<%= form_with model: @user, url: registration_path, html: { novalidate: true } do |form| %>
<div class="field">
<%= form.label :email_address, "Email" %>
<%= render "shared/field_error", form: form, attribute: :email_address %>
<%= form.email_field :email_address,
required: true,
autocomplete: "email",
aria: field_aria(form, :email_address) %>
</div>
<div class="field">
<%= form.label :password, "Password" %>
<p id="<%= form.field_id(:password, :hint) %>" class="field-hint">
Use at least 12 characters. Spaces are allowed.
</p>
<%= render "shared/field_error", form: form, attribute: :password %>
<%= form.password_field :password,
required: true,
minlength: 12,
autocomplete: "new-password",
aria: field_aria(form, :password, hint: true) %>
</div>
<%= form.button "Create account", data: { turbo_submits_with: "Creating account..." } %>
<% end %>
The view calls shared/error_summary and shared/field_error. We define those in the next section.
Rails Validation Errors
Active Model collects validation errors on model.errors. To present them accessibly you need two pieces: a message beside each invalid field, and a summary at the top of the page.
Field-Level Errors
This partial renders the first error for an attribute, using the same ID that field_aria references:
<%# app/views/shared/_field_error.html.erb %>
<%# locals: (form:, attribute:) %>
<% messages = form.object.errors[attribute] %>
<% if messages.any? %>
<p id="<%= form.field_id(attribute, :error) %>" class="field-error">
<span class="field-error__prefix">Error:</span>
<%= messages.first %>
</p>
<% end %>
The <%# locals: (...) %> comment is a strict locals declaration (Rails 7.1 and later), which makes the partial's contract explicit.
The Error Summary
A page-level summary tells users how many problems exist and lets them jump to each one. The links point to the field IDs that Rails generates (the model's param_key plus the attribute name). Radio groups need a special anchor, because the group has no single input ID, so the partial accepts an optional anchors hash.
<%# app/views/shared/_error_summary.html.erb %>
<%# locals: (model:, anchors: {}) %>
<% if model.errors.any? %>
<div class="error-summary">
<h2 id="error-summary-title" tabindex="-1" data-controller="focus">
<%= pluralize(model.errors.count, "problem") %> to fix
</h2>
<ul>
<% model.errors.each do |error| %>
<% if error.attribute == :base %>
<li><%= error.message %></li>
<% else %>
<% target = anchors.fetch(error.attribute, "#{model.model_name.param_key}_#{error.attribute}") %>
<li><a href="#<%= target %>"><%= error.message %></a></li>
<% end %>
<% end %>
</ul>
</div>
<% end %>
Three details make this accessible:
- The heading has
tabindex="-1"and thefocuscontroller, so focus moves to it after a failed submit. - Each message is a link that moves keyboard focus to the problem field when followed.
- Errors on
:base(not tied to a field) are shown as plain text, since there is nothing to link to.
Write Messages That Help
Model messages need to read well when displayed on their own, without the attribute name in front. Write them as complete, specific instructions, for example presence: { message: "Enter your name" }. If your app supports several languages, keep the messages in locale files so translations stay consistent. Our guide to Rails internationalization shows how, and remember to set the lang attribute on the html element for each locale (WCAG SC 3.1.1).
Render the Right Status
In Rails 8.1, when validation fails, re-render the form with status: :unprocessable_content. Turbo requires an error status to display the response of a failed form submission. Add the word "Error" to the page title on that response, because the title is the first thing a screen reader announces after a page load.
If a form spans several models or contains logic that does not belong in one Active Record class, a form object keeps validation tidy. See Rails form objects and when to use them. The accessible patterns in this article work the same way, because they only depend on errors.
Practical Example: An Accessible Rails Contact Form
Let us build a realistic contact form with text fields, a select, a radio group, a checkbox and a textarea. We keep the page novalidate and rely on server validation for the messages. The progressive client-side controller shown earlier can be layered on top.
Route
# config/routes.rb
Rails.application.routes.draw do
resources :contact_messages, only: %i[new create]
end
Model
An Active Model class avoids a database table for this example, and the same form works with an Active Record model.
# app/models/contact_message.rb
class ContactMessage
include ActiveModel::Model
include ActiveModel::Attributes
TOPICS = {
"support" => "Technical support",
"feedback" => "Feedback",
"partnership" => "Partnership"
}.freeze
attribute :name, :string
attribute :email, :string
attribute :topic, :string
attribute :needs_reply, :string
attribute :newsletter, :boolean, default: false
attribute :message, :string
validates :name, presence: { message: "Enter your name" }
validates :email, presence: { message: "Enter your email address" }
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP,
message: "Enter an email address like [email protected]",
allow_blank: true }
validates :topic, inclusion: { in: TOPICS.keys, message: "Choose a topic" }
validates :needs_reply, inclusion: { in: %w[yes no], message: "Choose whether you need a reply" }
validates :message, presence: { message: "Enter a message" }
validates :message, length: { minimum: 20,
message: "Enter a message of at least 20 characters",
allow_blank: true }
end
The allow_blank: true options prevent the same empty field from producing two messages at once.
Controller
# app/controllers/contact_messages_controller.rb
class ContactMessagesController < ApplicationController
def new
@contact_message = ContactMessage.new
end
def create
@contact_message = ContactMessage.new(contact_message_params)
if @contact_message.valid?
# Deliver an email or persist the message here.
redirect_to new_contact_message_path, notice: "Thanks, we will get back to you soon."
else
render :new, status: :unprocessable_content
end
end
private
def contact_message_params
params.expect(contact_message: %i[name email topic needs_reply newsletter message])
end
end
A Reusable Field Partial
Reusable partials are the best place to enforce accessibility, because every field built with them gets the same label, hint, error and ARIA wiring. The danger is the opposite: a partial that forgets one piece spreads that bug everywhere, so keep it small and test it.
<%# app/views/shared/_text_field.html.erb %>
<%# locals: (form:, attribute:, label:, field_type: :text_field, hint: nil, required: false, autocomplete: nil) %>
<div class="field">
<%= form.label attribute, label %>
<% if hint %>
<p id="<%= form.field_id(attribute, :hint) %>" class="field-hint"><%= hint %></p>
<% end %>
<%= render "shared/field_error", form: form, attribute: attribute %>
<%# field_type must come from trusted view code, never from user input. %>
<%= form.public_send(field_type, attribute,
required: required,
autocomplete: autocomplete,
aria: field_aria(form, attribute, hint: hint.present?)) %>
</div>
The View
<%# app/views/contact_messages/new.html.erb %>
<% content_for :title, "#{'Error: ' if @contact_message.errors.any?}Contact us" %>
<h1>Contact us</h1>
<% if flash[:notice] %>
<div class="notice">
<h2 tabindex="-1" data-controller="focus">Message sent</h2>
<p><%= flash[:notice] %></p>
</div>
<% end %>
<%= render "shared/error_summary",
model: @contact_message,
anchors: { needs_reply: "contact_message_needs_reply_yes" } %>
<p>All fields are required unless marked optional.</p>
<%= form_with model: @contact_message, url: contact_messages_path, html: { novalidate: true } do |form| %>
<%= render "shared/text_field", form: form, attribute: :name, label: "Name",
required: true, autocomplete: "name" %>
<%= render "shared/text_field", form: form, attribute: :email, label: "Email",
field_type: :email_field, hint: "We only use this to reply to you.",
required: true, autocomplete: "email" %>
<div class="field">
<%= form.label :topic, "Topic" %>
<%= render "shared/field_error", form: form, attribute: :topic %>
<%= form.select :topic,
ContactMessage::TOPICS.map { |value, text| [text, value] },
{ include_blank: "Choose a topic" },
{ required: true, aria: field_aria(form, :topic) } %>
</div>
<%= tag.fieldset class: "field", aria: field_aria(form, :needs_reply).slice(:describedby) do %>
<legend>Do you need a reply?</legend>
<%= render "shared/field_error", form: form, attribute: :needs_reply %>
<div class="choice">
<%= form.radio_button :needs_reply, "yes", required: true %>
<%= form.label :needs_reply, "Yes, please reply", value: "yes" %>
</div>
<div class="choice">
<%= form.radio_button :needs_reply, "no", required: true %>
<%= form.label :needs_reply, "No, I am only sharing feedback", value: "no" %>
</div>
<% end %>
<div class="field">
<%= form.label :message, "Message" %>
<p id="<%= form.field_id(:message, :hint) %>" class="field-hint">
Tell us how we can help. Use at least 20 characters.
</p>
<%= render "shared/field_error", form: form, attribute: :message %>
<%= form.text_area :message, rows: 6, required: true,
aria: field_aria(form, :message, hint: true) %>
</div>
<div class="field choice">
<%= form.check_box :newsletter %>
<%= form.label :newsletter, "Send me the CodeCurious newsletter (optional)" %>
</div>
<%= form.button "Send message", data: { turbo_submits_with: "Sending..." } %>
<% end %>
What Gets Rendered
If someone submits the form with an empty name, the name field looks like this (attribute order may vary):
<div class="field">
<label for="contact_message_name">Name</label>
<p id="contact_message_name_error" class="field-error">
<span class="field-error__prefix">Error:</span>
Enter your name
</p>
<input required="required" autocomplete="name" aria-invalid="true"
aria-describedby="contact_message_name_error"
type="text" name="contact_message[name]" id="contact_message_name">
</div>
Focus lands on the summary heading, the summary links to #contact_message_name, the label names the field, the error is both visible text and a programmatic description, and the invalid state is exposed. For a group of checkboxes (for example topics of interest), wrap the Rails collection_check_boxes output in a fieldset with a legend:
<fieldset class="field">
<legend>Which topics interest you? (optional)</legend>
<%= form.collection_check_boxes :interest_ids, Interest.order(:name), :id, :name do |box| %>
<div class="choice">
<%= box.check_box %>
<%= box.label %>
</div>
<% end %>
</fieldset>
This assumes a has_many :interests association on your model.
Testing Form Accessibility
No single tool tells you a form is accessible. Combine several approaches.
Manual Checks
- Keyboard only. Unplug the mouse. Tab through the form. Can you reach and operate every control? Is focus always visible? Does the order make sense? Can you leave every widget?
- Zoom and reflow. Zoom the browser to 200% and narrow the window to about 320 CSS pixels. Check that labels, errors and buttons remain visible without horizontal scrolling.
- Screen readers. Try at least one, such as NVDA or JAWS on Windows, VoiceOver on macOS and iOS, or TalkBack on Android. Different combinations of screen reader and browser announce things differently, so no single result is representative of every user. Listen for label, role, required state, descriptions and errors.
- Real users. Nothing replaces feedback from people who use assistive technology every day.
Browser Tools and Automated Checks
Chrome DevTools and Firefox include accessibility inspectors that show the accessible name, role and description of any element. Lighthouse, axe DevTools, WAVE and Accessibility Insights flag many common problems such as missing labels and low contrast.
Automated tools find only part of the problem. They can tell you a label is missing, but not whether a label is meaningful, whether the focus order makes sense, or whether an error message is understandable. A clean automated report is a good sign, not proof of full accessibility.
Testing in Rails
An integration test can check that the HTML contains the right associations without a browser:
# test/integration/contact_messages_test.rb
require "test_helper"
class ContactMessagesTest < ActionDispatch::IntegrationTest
test "invalid submission links errors to fields" do
post contact_messages_path, params: { contact_message: { name: "" } }
assert_response :unprocessable_content
assert_select "#error-summary-title", text: /problems to fix/
assert_select "a[href='#contact_message_name']", text: "Enter your name"
assert_select "#contact_message_name[aria-invalid=true][aria-describedby~=contact_message_name_error]"
assert_select "#contact_message_name_error", text: /Enter your name/
end
end
A system test runs in a real browser, so it can check focus behavior:
# test/system/contact_form_test.rb
require "application_system_test_case"
class ContactFormTest < ApplicationSystemTestCase
test "moves focus to the error summary after a failed submit" do
visit new_contact_message_path
click_button "Send message"
assert_selector "#error-summary-title:focus"
assert_link "Enter your name", href: "#contact_message_name"
field = find_field("Name", exact: true)
assert_equal "true", field["aria-invalid"]
assert_equal "contact_message_name_error", field["aria-describedby"]
end
end
If you use RSpec, the axe-core-rspec gem lets you run axe inside a system spec, for both the empty form and the error state:
# spec/system/contact_form_accessibility_spec.rb
require "rails_helper"
RSpec.describe "Contact form accessibility", type: :system do
it "has no automatically detectable violations" do
visit new_contact_message_path
expect(page).to be_axe_clean.according_to(:wcag2a, :wcag2aa)
end
it "has none in the error state" do
visit new_contact_message_path
click_button "Send message"
expect(page).to be_axe_clean.according_to(:wcag2a, :wcag2aa)
end
end
These tests protect against regressions, which is especially valuable when many forms share a partial.
Common Accessibility Mistakes
Here are the problems that show up most often in real code reviews, and what to do instead.
- Missing labels. Inputs with no
labelor with a label that is not linked. Fix: always pairlabel forwith a matchingid(Rails does this when you useform.label). - Placeholder-only instructions. Hints that vanish while typing. Fix: use a persistent label and visible help text linked with
aria-describedby. - Unclear error messages. "Invalid" or "Something went wrong". Fix: say what is wrong and how to fix it.
- Inaccessible custom controls.
divandspanelements acting as buttons, selects or checkboxes. Fix: use native elements, and only build custom ones when necessary, with full keyboard and ARIA support. - Missing focus indicators.
outline: nonewith no replacement. Fix: provide a high-contrast:focus-visiblestyle. - Color-only error states. A red border and nothing else. Fix: add visible error text and
aria-invalid. - Incorrect ARIA usage. Adding
aria-labelwhere a visible label belongs,role="button"on abutton,aria-requirednext torequired, oraria-invalid="true"on a field that is still valid. Fix: remember that no ARIA is better than bad ARIA, and ARIA changes only the accessibility tree, not behavior. - Moving focus unpredictably. Auto-focusing fields on load or stealing focus during typing. Fix: move focus only when the user needs to be taken somewhere new.
Best Practices
Use this checklist when designing, implementing and testing forms. Items in the first group correspond to WCAG 2.2 level A and AA success criteria. Items in the second group are recommendations that improve quality beyond the minimum.
Requirements (aim for WCAG 2.2 AA)
- Every control has a visible, programmatically associated label (SC 1.3.1, 2.4.6, 3.3.2).
- Visible label text matches the accessible name (SC 2.5.3).
- Personal data fields use appropriate
autocompletevalues (SC 1.3.5). - Required fields are identified in text and with
required, not by color alone (SC 1.4.1, 3.3.2). - Related controls are grouped with
fieldsetandlegend(SC 1.3.1). - Errors are identified in text, tied to the field, and say how to fix the problem (SC 3.3.1, 3.3.3).
- Every function works with a keyboard and there are no keyboard traps (SC 2.1.1, 2.1.2).
- Focus order is logical and focus is always visible and not hidden by sticky content (SC 2.4.3, 2.4.7, 2.4.11).
- Text has at least 4.5:1 contrast, and borders and focus indicators at least 3:1 (SC 1.4.3, 1.4.11).
- Controls meet the minimum target size (SC 2.5.8).
- Status messages are announced without moving focus (SC 4.1.3).
- Changing a control does not cause an unexpected context change (SC 3.2.2).
- Users do not have to re-enter information, and authentication allows paste and password managers (SC 3.3.7, 3.3.8).
- Legal, financial or data-changing submissions can be reviewed or reversed (SC 3.3.4).
Recommendations
- Prefer native elements and use ARIA only when native HTML cannot express the behavior.
- Show an error summary at the top of the page, and move focus to it after a failed submit.
- Add "Error" to the page title when validation fails.
- Validate after the user leaves a field or on submit, not on every keystroke.
- Use
:user-invalidinstead of:invalidfor styling. - Use button text that describes the result, such as "Send message".
- Keep one reusable, tested partial or component for field markup.
- Test with keyboard, zoom, at least one screen reader, automated tools and real users.
Conclusion
Accessible forms are not a special feature added at the end. They are the natural result of a handful of good habits. Start with semantic HTML so every control has a role, a name and keyboard behavior. Add clear labels and instructions that stay visible. Explain required fields in words. Validate on the server first, then enhance with the client. Make errors specific, visible, and programmatically tied to their fields. Keep focus visible, keep focus order logical, and move focus deliberately after validation, success and dynamic changes.
In Rails, form_with and the form helpers give you solid HTML, but accessibility remains your responsibility: write meaningful labels, link hints and errors with aria-describedby, mark invalid fields with aria-invalid, and test the result. A small helper, two partials and a Stimulus controller are enough to make all of that consistent across your application.
Pick one form in your current project and run the keyboard test today. What you find will show you where to start, and every barrier you remove makes the form better for everyone who uses it.