One of the biggest impediments to using forms effectively is understanding and navigating their layout. To
assist readers, always clearly label form controls using the label
element:
<label id="fname-label" for="fname">First name:</label>
<input type="text"
id="fname"
name="first-name"/>
The for
attribute is used to explicitly tie the label to its control. This attribute should
be included even if the label
also contain its control:
<label id="q1a-label" for="q1a">
<input type="radio"
id="q1a"
name="q1-answer"/> a. Apples
</label>
Note
If a form control is not identified by a label
, use the aria-labelledby
attribute on the control to identify the element containing the label.
When including additional instructions — for example, text limits or character restrictions —
try to include these within the label so that the information is immediately available to the reader.
When this is not possible, attach an aria-describedby
attribute to the control identifying
the element containing the additional instructions:
<label for="uname">User name:</label>
<input type="text"
id="uname"
name="username"
aria-describedby="username-req" />
<span id="username-req">
User names must be between 8 and 16 characters in
length and contain only alphanumeric characters.
</span>
The HTML5 required
attribute should always be attached to required fields so readers using
assistive technologies can be made aware in the absence of visual cues:
<input type="text"
id="uname"
name="username"
aria-describedby="username-req"
required="required"
aria-required="true"/>
Note
Including the aria-required
attribute is encouraged, as not all assistive technologies
may yet recognize the new HTML5 attribute.
Validation
When a form contains invalid data that needs to be corrected by the reader, attach the
aria-invalid
attribute to each field so that assistive technologies can quickly identify
the fields and move the reader to them:
if (country.value == 'US' && zip.value = '') {
zip.setAttribute('aria-invalid', true);
}
else {
zip.setAttribute('aria-invalid', false);
}
Do not attach the aria-valid
to any form element by default. Until the reader submits a form,
the fields in it are neither valid nor invalid.
To improve the experience for all readers, consider using the new HTML5 pattern
attribute on
form fields that can be validated by simple regular expressions. The reader will be alerted immediately
of problems instead of having to wait until submission. The title
attribute should also be
attached whenever using pattern
validation to explain the requirement. A username field
could restrict the number and type of characters as follows:
<input type="text"
id="uname"
name="username"
aria-labelledby="username-label"
pattern="[A-Za-z0-9]{8,16}"
title="User names must be 8 to 16 alphanumeric characters"
required="required"
aria-required="true" />