HTML5 and Accessible Forms - Pro HTML5 Accessibility: Building an Inclusive Web (2012)

Pro HTML5 Accessibility: Building an Inclusive Web (2012)

C H A P T E R 8

HTML5 and Accessible Forms

In this chapter, you'll learn about creating accessible forms in HTML5. The good news is that many techniques you might have used previously to create accessible forms using HTML 4 still apply when using HTML5. You'll also have a look at some new elements, as well as how the new HTML5 elements allow you to do more form validation natively within the browser, without the need for complex scripting.

If you don't know about creating accessible forms in HTML4, don't worry—I'll cover it all from scratch.

Designing an Accessible Form User Interface

Many of the principles you learned from the last chapter about creating accessible data tables also apply to the creation of accessible forms using HTML5. In general, the mantra “KISS” applies—and not just to accessible forms!

Forms really do benefit from a clear, simple, and concise layout. At all times, you should avoid adding any unnecessary complexity, and under the hood of your forms you need to create programmatic associations between the input fields, check boxes, and other elements and their corresponding labels. These practices are at the heart of creating accessible forms with HTML5.

Forms are, of course, very different from data tables. Forms are interactive, and data tables aren't. Their interactive nature does add a level of complexity when it comes to making your forms more accessible. In particular, the interactive nature of forms brings up questions about how you should approach form validation, as well as what you should do when there is an error on the part of the end user. How do you make sure the error message is accessible? There are two parts to the answer: you must first let the user know there is an error, and then inform the user of what she needs to do to correct the error. I'll say more about that later, but these are the principle concerns of accessible error recovery.

Some Forms Good Practices

You already saw some simple forms in Chapter 3, as well as some form-validation techniques using scripting. To be polite about it, doing form validation using some of the JavaScript-heavy techniques isn't a lot of fun. It's often complex and awkward. The technique of creating more accessible error messages using earlier versions of HTML isn't as bad.

First, I'll introduce some of the new input types and elements in HTML5. You'll see how these new elements are designed to be easier to author and how they reduce the need for complex validation using scripting. You'll also see accessible error messaging and learn some practices that lead you to create more accessible and usable forms—forms that are, again, both easier to author and use. So it's a win-win approach.

Image Note Much of what you'll come across in HTML5 is ported over from the Web Forms 2.0 spec of the Web Hypertext Application Technology Working Group (WHATWG). The idea was that Web Forms 2.0 was an extension to the forms features found in HTML 4. Web Forms 2.0 provided new input fields, as well as attributes for defining constraints, a repeating model for declarative repeating of form sections, new DOM interfaces, as well as DOM events for validation and dependency tracking. Web Forms 2.0 was also an attempt to document existing practices. If you fancy some nerd train spotting, point your browser to www.whatwg.org/specs/web-forms/current-work.

Differences in FORM Elements Between HTML 4 and HTML5

In HTML5, there are 13 new elements, and a host of new attributes. However, there are also many existing elements that might well be familiar to you from HTML 4 and are still valid. So it's worthwhile to look at them again.

In HTML 4, there were a number of elements you could use to create your various input boxes, combo boxes, and so on. These were used in conjunction with the FORM element to specify:

· The layout of the form (defined by the controls used in the form, their order, and position).

· The page or script that would handle the completed and submitted form (which takes the form of the action attribute).

· The method by which user data would be sent to the server (the method attribute, such as post).

In HTML 4, a FORM action would take the following general form:

<FORM action="http://yoursite.com/contact" method="post">
...form details...
</FORM>

This basic syntax remains the same in HTML5. Within the form itself, various controls could (and, indeed, still can) be defined to allow the user to interact with the form, to specify the nature of the interactions, and to spell out relevant requirements that each control could impose. We'll review these controls and the criteria for their use in the following sections.

The INPUT Element

The INPUT element is used for the user to enter data such as text strings (name, address, and so on) or numbers. In HTML 4, the INPUT element has various attributes that determine what type of INPUT the form control is. There are several HTML 4 INPUT element types, as listed here:

· text

· password

· checkbox

· radio

· submit

· reset

· file

· hidden

· image

· button

All of these INPUT element types create a control within the browser, and the browser has certain behaviors that are inherited with these types. If an input type is “password,” the browser displays a series of asterisks (****) instead of the real text. We'll look at the new HTML5 input types a little later.

The syntax for the INPUT types takes the following form:

<input type = "text">
<input type = "password">
<input type = "checkbox">

The syntax in HTML5 for the new types follows the same structure.

SELECT, OPTGROUP, and OPTION Elements

In HTML 4, you find the SELECT, OPTGROUP, and OPTION elements.

The SELECT element creates a menu in the browser. Each of the choices in the menu is represented by an OPTION element. If any of the OPTION element items need to be grouped together, the OPTGROUP element can be used by authors to group choices logically. This is useful if there is a long list of options for the user and you want to break them up into related sections.

This takes the form shown in Listing 8-1.

Listing 8-1. SELECT, OPTGROUP, and OPTION Elements

<select>
<optgroup label="Electric Guitars">
<option value="Fender">Fender</option>
<option value="Gibson">Gibson</option>
<option value="Rickenbacker">Rickenbacker </option>
</optgroup>
<optgroup label="Acoustic Guitars">
<option value="Gretsch">Gretsch</option>
<option value="Martin">Martin</option>
<option value="Lowden">Lowden</option>
</optgroup>
</select>

The fieldset and legend Elements

The idea behind the <fieldset> and <legend> elements in HTML 4 is that they give more structure to your forms. The <fieldset> element is used to group form controls thematically, and the <legend> is like a caption for the contents of the <legend> element's parent <fieldset>. A bit of a mouthful! If you remember, we already looked at using these elements in the Chapter 3.

Image Note All the preceding elements are still valid in HTML5.

The <label> Element

The <label> is very important for the creation of accessible form controls. The <label> element is used to create a specific label for a control. This label allows you to create (you guessed it) a programmatic association between the <label> name and the control itself. This allows assistive technologies (AT) such as a screen reader to understand what the purpose of the INPUT element is. A suitable label for the INPUT control is important because as soon as the INPUT field has focus, if it's labeled correctly, the <label> name will be announced by the screen reader.

The for/id Method

Accessible, well-labeled form controls in HTML 4 use a method called the for/id method. This is where the label that you use to identify the INPUT element takes the form <label for="somename">, and it is programmatically associated with the INPUT control by giving the same value to theINPUTs id, <input id="somename">. Listing 8-2 details this method.

Listing 8-2. Using for/id Combinations to Make an INPUT Text Box Accessible

<h1>Create new account</h1>
<form>
<label for="username">E-mail address:</label>
<input id="username" type=email name=mail>

<label for="password1">Password:</label>
<input id="password1" type=password name=pass>

<input type="submit" value="Login">
</form>
</body>
</html>

The name attribute is also designed to specify the name of the INPUT element and is useful for identifying groups of controls. It's also used for form submission. It isn't announced by AT.

So the text that is contained between <label>[…]</label> is announced by AT as soon as the corresponding INPUT field has been given focus via the keyboard. When you want to be sure that a screen reader user will be able to access some information in your form, you can include it in the form's <label>.

HTML5 Labeling of Form Controls

The HTML5 specification outlines another way of labeling a form control that doesn't use the preceding for/id method. This way isn't actually new, and it's where you literally wrap the form control in a <label>. It takes the following general form:

<label>Text to label control<input type="text"></label>

Image Note As mentioned, this method isn't new and was in HTML 4. In HTML 4, you can also technically assign several label elements to a form control by using the for attribute of various labels to point at the control. - However, you can no longer do this in HTML5. Also, this method was poorly supported by AT.

In the HTML5, the specification suggested that you use either the for/id method or wrap the label in the control. In the following line of code, I combined the two methods and wrapped the control in a label, while also using the for/id method. This takes the form shown next:

<label for="a11y_label"> Text to label control <input type="text" id="a11y_label"> <label>

This worked fine for me when testing it in Safari 5.1 using VoiceOver on Mac 10.7 (Lion). I also tried running some more text beyond the input box, and this was also announced by the screen reader. For example:

<label for="a11y_label"> Text to label control <input type="text" id="a11y_label"> some extra
useful info!</label>

The interesting thing is that Steve Faulkner, a friend and an accessibility expert with The Paciello Group (TPG), ran some extensive tests and found that neither method worked very well on Safari 5 with VoiceOver, but I find that it now does (or seems to). So it's possibly a sign of improvement in terms of support for these structures.

Image Caution Jared Smith published a very interesting article on WebAIM titled “Semantic Automation.” Semantic automation is used by VoiceOver to repair certain broken web content. This can mean that the test results I found are a product of advanced heuristic evaluation and not the application of HTML5 markup. I'm referring here not to the for/id method (which is tried and tested and bulletproof), but to the method recommended in the HTML5 specification for wrapping a control in a label. For more detail, see the WebAIM blog athttp://webaim.org/blog/semantic-automation.

Although this newer (sic) method suggested by the HTML5 specification to identify a control by wrapping it in a label doesn't use the explicit association of the for/id method, as mentioned, I found it to work OK with VoiceOver (but see the earlier Caution). However, in terms of making your forms more bulletproof and working with older legacy AT, I recommend sticking with the for/id method for now. Don't see this as a limitation. The markup is straightforward as you can see, and the for/id method is very well supported. You can use it with confidence, knowing that screen-reader users will also be able to easily use your forms.

Also, HTML5 has the same radio buttons, check boxes, and so on that you will recognize from HTML4.

New HTML5 Elements

The following is a list of the new HTML5 form elements and attributes.

The <datalist> Element and the list Attribute

HTML5, to expand on what the SELECT and OPTION elements can do, gives you the ability to present the user with suggested predefined options. You do this by using the new <datalist> element and list attribute.

You use the @list value to point to the same ID in the <datalist> element. In Listing 8-3, I added a title attribute to give the screen-reader user a heads up about how to use the control.

Listing 8-3. Using <datalist>

<input type="text" list="suggested_DAW_options" title="Press down arrow to see selections">
<datalist id="suggested_DAW_options">
<option value="Logic">
<option value="Ableton Live">
<option value="Digital Performer">
<option value="Cubase">
<option value="Sonar">
<option value="Cockos Reaper">
</datalist>

The <output> Element

This new element represents the result of a calculation. It's used in conjunction with the for attribute. You can add values from various form elements, for example. Listing 8-4 is inspired by an example on the W3Schools.com web site.

Listing 8-4. Using <output>

<form oninput="z.value=parseInt(x.value)+parseInt(y.value)">
Enter Value 1: <input type="number" name="x" value="0" />
Enter Value 2: <input type="number" name="y" value="0" />= <output name="z" for="x y">
</output>
</form>

Image Note There are some interesting examples of the <output> element in use at http://html5doctor.com/the-output-element.

The <progress> and <meter> Elements

Both the <progress> and <meter> elements display similarly in the browser. Figure 8-1 shows a screen shot from Firefox 9. Figure 8-2 shows the same progress bar in Opera 11.6.

Image

Figure 8-1. The <progress> element in Firefox 9

Image

Figure 8-2. The <progress> element in Opera 11.6

Image Note Neither of the preceding examples displays the <progress> data in a way that is accessible out of the box, and I haven't seen an accessible implementation. The closest thing to one that I have seen is a part of the excellent work that Hans Hillen (TPG) and Chris Blouch (AOL) are doing as a part of the Aegis project in developing JQuery-powered, accessible WAI-ARIA-enabled widgets and controls. For more information, point your browser to http://access.aol.com/aegis/#goto_progressbar.

New HTML5 INPUT Types

One of the really cool things about HTML5 is the new form controls–in particular, the various input types. These are going to be very useful for authors because they take away some of the complexity of validation (which isn't a lot of fun). These controls have particular behaviors and models of interaction, as you shall see. We are used to rather simple input types in earlier versions of HTML, such as Text, Password, or Search, for example.

Image Note You can write the following types with or without the opening double quotes (") or closing double quotes ("). So both <input type="tel"> and <input type=tel> are valid. I wrote them here as <input type="tel"> because it's my preference. When a user agent comes across a type that it doesn't understand, it will default to displaying the control as generic text-type input.

In HTML5, the type state determines what kind of input the control is. All of the new types pretty much do what they say on the tin. The full list of types is described in the following short sections.

Hidden (type=hidden)

This takes the following form:

<input type="hidden">

The hidden type represents some value that isn't to be seen by the end user.

Telephone (type=tel)

This takes the following form:

<input type="tel">

Although this type is obviously for inputting a phone number, no particular phone pattern is required. This is because various valid types of phone numbers are available around the world.

URL (type="url")

This takes the following form:

<input type="url">

This control is for inputting a URL. Both this input type and the next one (for email) do expect (and enforce) the expected syntax. This is useful for client-side validation.

Email (type="email")

This takes the following form:

<input type="email">

This control is for inputting an email address. As mentioned, both this input type and the previous type (for a URL) do expect (and enforce) the expected syntax.

Password (type="password")

This takes the following form:

<input type="password">

This is used for inputting a password. The form for this is shown in Figure 8-3, and it should be familiar to you.

Image

Figure 8-3. The password input type

What you might not be familiar with is how a screen reader behaves when it gives focus to the password control. Consider the following code used to generate the control:

<form>
<label for="pword"> Password:</label>
<input type="password" id="pword" name="pswrd">
</form>

A <label> for the control informs the screen-reader user about the purpose of the control. Then when it receives focus and the screen-reader user starts to input some characters, the output is (depending on the screen reader) a series of clicking noises that sound after each key is pressed. If a series of asterisks appear in the control, the output is “star, star, star” and so on. In other words, the actual characters that are being output are not announced so that a blind user's privacy is maintained.

Date and Time Controls

The following are new input types for adding date and time controls to HTML5 forms. They take the following form:

<input type="datetime">
<input type="date">
<input type="month">
<input type="week">
<input type="time">
<input type="datetime-local">

Let's put them together into a simple form, as detailed in Listing 8-5, and see how the different browsers render them.

Listing 8-5. Using Date and Time Controls

<form>
<label for="type_datetime">Datetime:</label>
<input type="datetime" id="datetime">

<label for="type_date">Date:</label>
<input type="date" id="type_date">

<label for="type_month">Month:</label>
<input type="month" id="type_month">

<label for="type_week">Week:</label>
<input type="week" id="type_week">

<label for="type_time">Time:</label>
<input type="time">

<label for="type_datetime-local">Time:</label>
<input type="datetime-local" id="type_datetime-local">
</form>

Listing 8-6 shows some simple Cascading Style Sheets (CSS) used to hold it together.

Listing 8-6. CSS for the Date/Time Form

label {
width: 3em;
display: block;
margin:5px;
}

input {
width: 5.5em;
float: left;
display: block;
margin-top:-25px;
margin-left:90px;
padding:5px;
}

And finally, Figures 8-4, 8-5, and 8-6 are screen shots of the form in Safari 5.1, Firefox 9, and Opera 11.6, respectively.

Image

Figure 8-4. New date and time controls in Safari

Image

Figure 8-5. New date and time controls in Firefox

Image

Figure 8-6. New date and time controls in Opera

Notice the difference between how the three browsers render the controls. Safari displays a spinner control to the right of each of the input controls. Firefox doesn't, and Opera gives both a spinner control for the <datetime> input as well as the time and datetime-local controls.

Image Note A spinner control is used to adjust values up or down by selecting the appropriate arrow. At the time of this writing, they are not natively accessible or focusable via the keyboard in Safari 5.1 (Mac). They don't display in IE9, or Firefox 8 (PC). Although the calendar date picker does display in Opera, Opera isn't a very screen reader friendly browser. By the time you read this Internet Explorer 10 will have shipped, and it promises better HTML5 support. Will it do so in practice? Time will tell.

Number (type=""number"")

The number input control takes the following form:

<input type="number">

It's a new type of control for representing a number. If you build it using the following code and look at it in some different browsers, you'll see the variability in the way browsers render HTML5 by default:

<form><label for="type_number">Enter a Number:</label>
<input type="number" id="type_number">
</form>

Figures 8-7, 8-8, and 8-9 show how various browsers render this code.

Image

Figure 8-7. The "number" input type in Safari

Image

Figure 8-8. The "number" input type in Opera

Image

Figure 8-9. The "number" input type in Firefox

Range (type="range")

The range input type is an interesting new control. It allows the user to enter values into a form using a slider control. This code takes the following form:

<form>
<label for="type_range">Use slider to enter a value:</label>
<input type="range" title="You use the left and right arrow keys to move the values up an down." id="type_range">
</form>

The range input control is displayed visually in browsers that support it, as shown in Figures 8-10 and 8-11.

Image

Figure 8-10. The range input in Safari

Image

Figure 8-11. The range input in Opera

Range isn't supported, at the time of this writing, in IE9 (PC) or Firefox 9 (MAC/PC). Chrome (PC) does support it, however. What is interesting is that, in testing, the Chrome browser not only has native keyboard access to the control, but it also feeds back the current value of the slider. As far as I can tell, no other browser currently does that. To make the slider control more accessible, you might have to provide a scripted solution in order for AT to be able to announce the current value of the slider so that the screen-reader user can know where they are at.

Image Note For some really good examples of accessible and unobtrusive JavaScript-powered, HTML5, range-type controls, point your browser at www.frequency-decoder.com/demo/fd-slider. You can see how these polyfills often don't use the native range, but use a combination of CSS to style the control, WAI-ARIA to add the semantics, and JavaScript to capture interactions.

Both the number and range input types can take the following new HTML5 attributes: min and max. These attributes allow you to set both minimum and maximum values that a numerical control or, indeed, the range control can accept.

They take the following form:

<input type="range" min="1" max="5">

There is also the new step attribute, which allows you to set in a granular way the amount that input values jump up or down. If you want user input to jump, up or down, by a value of 5, you use code like the following:

<input type="number" step="5">

Color (type="color")

This control takes the following form:

<input type=”color”>

This is a color picker type input. To my mind, it's a strange control for forms because I struggle to think of uses for it. At time of this writing, only Opera has an interesting rendering of the control in the browser (shown in Figure 8-12).

Image

Figure 8-12. The color input in Opera

The rest of the controls should be familiar to you from HTML 4, such as check boxes, radio buttons, file upload controls, Submit buttons, Reset buttons, and Search inputs.

New HTML5 Form Attributes

The following sections list attributes taken from the “HTML5 differences from HTML4” document that are new to HTML5. You can find the document at www.w3.org/TR/html5-diff.

The autofocus Attribute

A new autofocus attribute (@autofocus) can be specified on the input control (except when the type attribute is hidden) and on the select, textarea, and button elements. It provides a declarative way to focus a form control during page load.

Using the @autofocus attribute takes the following general form:

<input type="text" name="firstname" autofocus>

It's very easy to author and add to your projects. The @autofocus attribute is an interesting new attribute in HTML5, and it has the potential to be useful in creating accessible error recovery. This can be achieved by using it to autofocus on the first field that has an error message after the form has been validated. If this method is used, it is important to ensure that any inline description of the error message is also included as a part of the label of the control, or that aria-described by is used to point at the error if that exists on another part of the page.

It isn't enough to just use the autofocus attribute to position the focus on a field, even if it's the correct field where the error occurs, and not clearly explain what the error is and how to fix it.

New INPUT Element Attributes

The INPUT element has several new attributes to specify constraints: autocomplete, min, max, multiple, pattern, and step. Some of these attributes were discussed in the section about the range input type. There is also a new list attribute that can be used together with the datalistelement.

The dirname Attribute

The input and textarea elements have a new attribute, named dirname, that causes the directionality of the control as set by the user to be submitted as well.

New TEXTAREA Element Attributes

The TEXTAREA element also has two new attributes: maxlength and wrap. These attributes control the maximum input length and the submitted line-wrapping behavior.

The novalidate Attribute

The FORM element has a novalidate attribute that is used when you don't want to perform any validation and just submit the form, in all circumstances.

New input and button Element Attributes

The input and button elements have formaction, formenctype, formmethod, formnovalidate, and formtarget as new attributes. If present, they override the action, enctype, method, novalidate, and target attributes on the FORM element.

The placeholder Attribute

A new placeholder attribute can be specified on the input and textarea elements. It represents a hint intended to aid the user with data entry, as shown here:

<input type=email placeholder="mr.pussels@bigcat.com">

The new @placeholder has codified the use of placeholder text within form fields. I have mixed feelings about this. Traditionally, placeholder text performed a couple of tasks. First, to aid a sighted person in understanding what the input control is for by displaying a sample of the kind of content it requires. It was also used to describe the purpose of the control to AT (when it didn't in the early days of the Web), support the title attribute of the input type, or other labeling mechanisms.

However, this hasn't been the case for quite some time, and adding placeholder text like this created several problems—such as the contents of the INPUT control not being cleared if scripting was disabled, for example. Clearing the content of the input field on focus is certainly a useful technique, but in older user agents it begs the question of what happens when JavaScript is off. I'll tell you what happens. The text that's input from the user gets mixed with the placeholder content. For example, if you have an input type like the one just shown, for email, in earlier versions of HTML, and you input the string “josh@animalsanctuary.com”, if you didn't use script to clear the field or if it was off, you would get a string like the example in Figure 8-13.

Image

Figure 8-13. Placeholder text mixed with user input text

The good news is that when most older user agents, such as browsers, come across the placeholder attribute or any new HTML5 input types that they doesn't understand, most will just display an input box by default. For example, consider the code in Listing 8-7 and the resulting screen capture (Figure 8-14).

Listing 8-7. An HTML5 Input Type

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5 forms:Placeholder</title>
</head>
<body>
<h1> HTML5 Form placeholder</h1>
<form>
<label>Address: <input type="email" name="address" placeholder="mr.pussells@bigcat.com">
</label>
</form>
</body>
</html>

The resulting rendering in the browser is shown in Figure 8-14.

Image

Figure 8-14. HTML5 rendered as a text field by an older browser

Image Note In newer HTML5 browsers that support the @placeholder, the contents get cleared on focus, without the need for any scripting at all. This makes authoring easier. Also, the default behavior for older user agents means that you can use it without worrying too much about older user agents having problems.

One issue to be aware of, however, is the poor color contrast of the placeholder text. This will be problematic for low-vision computer users. For example, consider the screen shots from Safari 5.1 (Figure 8-15) and then Opera 11.5 (Figure 8-16).

Image

Figure 8-15. Color contrast of placeholder text in Safari

Image

Figure 8-16. Color contrast of placeholder text in Opera

Did you notice how poor the color contrast is? Poor color contrast can make it very difficult for people with vision impairments to see content on screen. Bear in mind that lots of people with vision impairments don't use AT at all. They get by using the browser controls to resize text or by using systemwide, high-visibility options and so on. So having good, strong color contrast in your web content is a great help.

In HTML5, you can style various input types, but you must target specific browsers, as well as mention the attribute that you want to style.

To style an input box to darken the placeholder text, you can use CSS3 selectors, which take the following form:

::-webkit-input-placeholder {
color: #333333;
}

:-moz-placeholder {
color: #333333;
}

Image Note There are vendor-specific prefixes for webkit browsers such as Safari and Chrome, as well as the prefixes for Mozilla or Gecko-based browsers. At the time of this writing, many browser manufacturers are starting to drop the need for a prefix on some CSS3 declarations. So rather than having to write vendor specific declarations, soon you might be able to just declare something like “border-radius” and the browser will just handle it correctly. IE9 is impressive in this regard but will need the “ms” prefix for some selectors.

The New form Attribute

The new form attribute for input, output, select, textarea, button, label, object, and fieldset elements allows for controls to be associated with a form. The idea is that the elements can be placed anywhere on a page, not just as descendants of the form element, and still be associated with a form. The specification gives the following example:

<label>Email:
<input type=email form=foo name=email>
</label>
<form id=foo></form>

However, this example doesn't really get across what the potential of this new pattern is. Now the form control can be separated from its parent and placed outside the <form>[…]</form> markup, if the author has a need to do this.

The example in Listing 8-8 should make this a little clearer.

Listing 8-8. Using the New form Attribute

<div id="form_container">
<form id="contact_1" action="post">
<label for="first_name"> First Name:</label>
<input type="text" id="first_name" name="fname">

<label for="second_name"> Last Name:</label>
<input type="text" id="second_name" name="lname">
<label for="mail">Your Email:</label>
<input type="email" id="mail" name="mail">
<input type="submit" id="submit" value="Contact Us!">
</form>
</div>

<div id="content_2">
<textarea id="extra_info" title="Enter extra Info here and tab back to submit form" form="contact_1" placeholder="Something more to say?">
</textarea>
</div>

Listing 8-9 provides a little CSS to render the form and give it some basic positioning and styling.

Listing 8-9. CSS for the form

<style type="text/css">

#form_container {
display:block;
width:100%;
max-width:190px;
font-family: Lucida Sans Unicode, Lucida Grande', sans-serif;
color: #C90;
background-color:#333;
margin:10px;
padding:10px;
border-radius: 19px;
}

#content_2 {
display:block;
max-width:190px;
font-family: Lucida Sans Unicode, Lucida Grande', sans-serif;
color: #C90;
background-color:#333;
margin:10px;
padding:10px;
border-radius: 15px;
}

label {
width: 3em; display: block; margin:5px;
}

input {
width: 9.5em;
float: right;
display: block;
margin-top:-40px;}

#extra_info {
width:90%;
max-width:inherit;
display: block;
font-family: Lucida Sans Unicode, Lucida Grande', sans-serif;
color: #C90;
background-color:#333;
border-radius: 15px;
}

#submit {
margin:10px;
}

::-webkit-input-placeholder {
color: #ffffff;
}

:-moz-placeholder {
color: #ffffff;
}
</style>

Figure 8-17 is a screen shot of the form taken from the Safari browser.

Image

Figure 8-17. The form attribute at work

This kind of pattern might become more popular, and certainly the ability to refer to an element outside of the traditional <form> structure has the potential to create, well, new forms (pardon the pun) of interaction. In this case, because I can add a title attribute to the text area the screen reader will be able to provide supplementary information to the user. The contents of the title attribute on a form control are output when the control is given focus, in the absence of a label. Giving a form control a title, instead of a label, is an acceptable way of providing accessible information to the end user provided that the purpose of the control is apparent also from its visual rendering. In this case, the text “Something more to say?” acts as a visual cue. You might find that you have other controls when building forms that you might not want to label.

As mentioned, this new form attribute can be added to input, output, select, textarea, button, label, object, and fieldset elements. As always, the issue is one of support for them in both the browser and the AT. In time, as this new pattern gains ground, support undoubtedly will improve.

Image Note The use of the title attribute or (@title) on form controls is different from using the @title attribute on an image. Although you cannot be sure if the screen reader will pick up on the contents of the @title on an image or graphic, when used on form controls it's a lot more robust. So you can use it with confidence.

The New required Attribute

The new required attribute (or @required) applies to input, select, and textarea controls and plays an important part in form validation and, indeed, error recovery. It indicates that the user has to fill in a value in order to submit the form. For a select control, the first option element has to be a placeholder with an empty value, as shown in the following snippet:

<label>Color: <select name=color required>
<option value="">Choose one
<option>Red
<option>Green
<option>Blue
</select>
</label>

Support for the HTML5 @required is pretty good with new screen readers. The attribute won't be picked up by older screen readers at all. A way around this is to use a combination of the WAI-ARIA property aria-required="true" in conjunction with the HTML5 @required. The idea is that the older screen reader that supports WAI-ARIA but not HTML5, will pick up on the aria-required="true" property, and the net result will be that they will be informed that they have focused on a required control. The code for that (based on the preceding example from the spec) is as follows:

<label>Color: <select name=color required aria-required="true">
<option value="">Choose one
<option>Red
<option>Green
<option>Blue
</select>
</label>

There are some drawbacks from the example. First, a screen reader that understands both the HTML5 code required and the WAI-ARIA code aria-required=”true” will output “Required” twice. This can be a pain, in particular when there are lots of required fields. You can argue that it's a bulletproof method, but the user experience might leave a lot to be desired. Also, with this method, what about screen readers that don't understand either the HTML5 code or the WAI-ARIA code? In this case, they won't be able to do anything useful for the end user.

Unfortunately, there is no way for you as an author to detect what kind of AT a person is using. A more robust way of being backward compatible with older technology is to include the word “Required” within the label of the control. This takes the following form:

<label> Choose a color [Required] </label>

It's rather simple and will work for both older user agents and newer ones. It's also an older method of making forms accessible that still has some traction-there are a few! However, you might not want to have the word “[Required]” in the label of your control, but that's your call. The advantage is that it will work for both sighted users and screen-reader users with both old and new screen readers.

This issue in particular is suitable to highlight how there are similarities between some WAI-ARIA code forms and HTML5. In this case, there certainly seems to be a degree of redundancy between the two. The advantage of aria-required="true" in this case (as it will be in a lot of ARIA 1.0 cases) is that support was implemented in screen readers over the last couple of years, and at time of this writing is slightly ahead of HTML5. I am pretty sure, however, that this will all change when HTML5 support grows (as it currently is). Ultimately, how you decide to author should be based on testing and what is best for your needs. In the end, go with whatever works, though you might have to compromise somewhere along the line.

Image Note The @required isn't to be used when the type attribute is hidden or when an image or some button type such as a submit button is used.

The disabled Attribute

The fieldset element now allows the disabled attribute, which disables all descendant controls when specified, and the name attribute, which can be used for script access.

HTML5 Form Validation

Form validation is an important part of the under-the-hood mechanics of both getting good data from your users, as well ensuring that when there are errors you can be accurate when you inform the user of what went wrong. So validation plays a part as a stage-one process in error recovery also.

First (as mentioned earlier), you can use the required attribute and/or aria-required="true" (or a combination if the two).

Opera has an interesting implementation of the required attribute if the form is submitted without a required field being filled in, as shown in Figure 8-18.

Image

Figure 8-18. Opera 11.6 required field

Firefox also has an interesting implementation in such cases: it also highlights the required field in red by default. You can see the effect in Figure 8-19.

Image

Figure 8-19. Firefox 9 required field

In terms of “in the browser” validation, Firefox also has a very nice feature: the message “Please fill out this field” is announced by the screen reader-at least in my testing with JAWS 12 and Firefox 9 (PC). This is excellent. Not only does the field that the error occurs on receive focus, but the label is also read out again when focus is brought to the field. This is a perfectly acceptable, and it's an accessible way of performing both validation and error recovery. Chrome also displays an error message similar to the other browsers mentioned, but it's not accessible out of the box in the same way as it is in Firefox 9.

Sadly, none of these features are supported in IE9.

The Use of Patterns in HTML5 Forms

Within HTML5 forms, you can also check that the user input matches what is expected-so that you don't get a text string in a numeric field or so that you do get a proper email address. You can use the new pattern attribute to help with validation. This attribute tells the browser to look for a pattern after user input, so this can be a range of numeric characters or a particular text string. For example, a UK postal code can take the following form:

Image

Don't worry if this seems complex. There are lots of resources online, and I came across this one via the Thinkvitamin.com website, called “html5pattern.com,” that contains loads. So point your browser over there if you want to include these kinds of patterns in your projects.

Accessible Error Recovery

Accessible error recovery is a very important technique in the creation of forms that can be used by the widest possible audience. Therefore, it's important that any new methods you use in HTML5 have some degree of backward compatibility because not everyone is using the latest browsers or, as I have indicated time and again, the latest AT. So while the new HTML5 language is very powerful, the issue of user-agent support is a recurring limitation you have to provide for.

There are couple of stages to accessible error recovery you should be aware of:

1. Let the user know there is an error.

2. Let the user access the error, and provide instructions on how to fix it.

3. Allow the user to resubmit the form.

As you saw in the section on validation, some browsers do support the new HTML5 attributes like required and can provide focus to each field (depending on the source order in the code) that has an error. When the input field is marked up correctly with a proper <label>, in supporting browsers this is often enough information for a screen-reader user to fix the error. However, in tests this worked only in Firefox 9 with JAWS (from a screen-reader user's perspective). However, this is a good sign. Where there is support for these HTML5 methods to help with validation and, to some degree, error recovery, there is the possibility of being able to do both without authoring more complex error-recovery methods.

However, lots of browsers don't support this method at all. So how can you support the important issue of accessible error messaging in a way that will work with both older and newer browsers?

The following is a method of accessible error recovery that will work with both older and newer browsers.

Image Note While I came across a similar method on the WebAIM web site many years ago, this implementation comes from the “Standards Schmandards” website developed by Peter Krantz. Many thanks to Peter for allowing me to reproduce it here. As an aside, Peter is also doing lots of other interesting work in data visualization and systems interoperability. For more information, point your browser at www.peterkrantz.com.

This is a simple method that is pretty bulletproof. Consider the form shown in Figure 8-20.

Image

Figure 8-20. A registration form with required fields

Listing 8-10 shows the HTML for the form.

Listing 8-10. Code for the Registration Form

<p>Please complete the following form to create your account. </p>
<form name="registrationform" id="registrationform" method="post" action="index.php">
<fieldset>
<legend>Personal details</legend>
<div class="formrow"><div class="labelcontainer">
<label for="name">* Name:</label>
</div>
<div class="field">
<input name="name" type="text" id="name" maxlength="55" style="width:200px" title="Your name. Required information." />
</div>
</div><div class="formrow">
<div class="labelcontainer">
<label for="age">* Age:</label>
</div>
<div class="field">
<input name="age" type="text" id="age" maxlength="3" title="Your age. Required information."/></div>
</div>
<div class="formrow">
<div class="labelcontainer">
<label for="country">Country:</label>
</div>
<div class="field">
<select name="select" id="country" title="Your country of residence.">
<option value="1">Sweden</option>
<option value="2">United States</option>
<option value="3">Japan</option>
</select>
</div>
</div>
<div class="formrow">
<input type="submit" style="float:right;" value="Register" name="registerbtn"/>
</div>
</fieldset>
</form>

Now, if the form was submitted and both fields were left blank, the error message in Figure 8-21 would be displayed.

Image

Figure 8-21. Error message for required fields

The code to produce this error message is shown in Listing 8-11.

Listing 8-11. Code for the Error Message

<div id="validationerror">
<h2 id="errorsummary">2 errors were found in your registration.</h2>
<p>Please correct these errors and submit the form again:</p>
<ul>
<li id="er_128">
<a href="#name" onclick="setfocus('name')">
The Name field can not be empty.
Please enter your name.</a></li>
<li id="er_215">
<a href="#age" onclick="setfocus('age')">
The Age field can not be empty.
Please enter your age in years.</a></li>
</ul>
</div>

Some JavaScript is used to focus on the relevant field the user can use to address the problem:

function setfocus(objectid) { if(document.getElementById(objectid))
{ document.getElementById(objectid).focus(); }
}

The preceding code can be triggered via the keyboard, so it's perfectly accessible. The error messages are also very clear and give the user an overview of both the error and what can be done to remedy it. Pretty neat!

Using JQuery for Form Validation

There is also a good JQuery form-validation plug-in you can use to validate your forms and provide accessible error messages. Point your browser at the NOMENSA blog for an excellent tutorial on how to do it: www.nomensa.com/blog/2010/accessible-forms-using-the-jquery-validation-plug-in.

Conclusion

In this chapter, we looked some old, as well as new, HTML elements and attributes you can use to build accessible forms. Not all of the new elements are supported as of yet, but this will change. Also, you saw how to do some client-side validation, as well as some accessible error messaging. In the next chapter, we'll look at usability and user-centered design.