Web Foundations

Better web forms with HTML5, Part 2

By Adam Roberts

This is the second article in our series on building better web forms with HTML5. For the first article visit Better web forms with HTML5, Part 1.

We have looked at why HTML5 forms are great for web developers of all levels in our previous article, so now let’s dive in further and look at HTML5 form attributes.

HTML5 Form Attributes

For years, developers have written (or copied and pasted) snippets of JavaScript to validate the information users entered into form fields: what elements are required, what type of data is accepted, and so on. HTML5 provides us with several attributes that allow us to dictate what is an acceptable value, and inform the user of errors, all without the use of any JavaScript.

Browsers that support these HTML5 attributes will compare data entered by the user against regular expression patterns provided by the developer (you). Then they check to see if all required fields are indeed filled out, enable multiple values if allowed, and so on. Even better, including these attributes won’t harm older browsers; they’ll simply ignore the attributes they don’t understand. In fact, you can use these attributes and their values to power your scripting fallbacks, instead of hardcoding validation patterns into your JavaScript code, or adding superfluous classes to your markup. We’ll look at how this is done a bit later; for now, let’s go through each of the new attributes.

The required Attribute

The Boolean required attribute tells the browser to only submit the form if the field in question is filled out correctly. Obviously, this means that the field can’t be left empty, but it also means that, depending on other attributes or the field’s type, only certain types of values will be accepted. Later in the chapter, we’ll be covering different ways of letting browsers know what kind of data is expected in a form.

If a required field is empty or invalid, the form will fail to submit, and focus will move to the first invalid form element. Opera, Firefox, and Chrome provide the user with error messages; for example, “Please fill out this field” or “You have to specify a value” if left empty, and “Please enter an email address” or “xyz is not in the format this page requires” when the data type or pattern is wrong.

Out of focus?

Time for a quick refresher: a form element is focused either when a user clicks on the field with their mouse, or tabs to it with their keyboard. For input elements, typing with the keyboard will enter data into that element.

In JavaScript terminology, the focus event will fire on a form element when it receives focus, and the blur event will fire when it loses focus.

In CSS, the :focus pseudo-class can be used to style elements that currently have focus.

The required attribute can be set on any input type except button, range, color, and hidden, all of which generally have a default value. As with other Boolean attributes we’ve seen so far, the syntax is either simply required, or required="required" if you’re using XHTML syntax.

Let’s add the required attribute to our sign-up form. We’ll make the name, email address, password, and subscription start date fields required:

    <label for="register-name">My name is:</label>
    <input type="text" id="register-name" name="name" required aria-required="true">
    <label for="email">My email address is:</label>
    <input type="text" id="email" name="email" required aria-required="true">
    <label for="url">My website is located at:</label>
    <input type="text" id="url" name="url">
    <label for="password">I would like my password to be:</label>
    <p>(at least 6 characters, no spaces)</p>
    <input type="password" id="password" name="password" required aria-required="true">
    <label for="rating">On a scale of 1 to 10, my knowledge of HTML5 is:</label>
    <input type="text" name="rating" type="range">
    <label for="startdate">Please start my subscription on:</label>
    <input type="text" id="startdate" name="startdate" required aria-required="true">
    <label for="quantity">I would like to receive <input type="text" name="quantity" id="quantity"> copies of <cite> The HTML5 Herald</cite></label>
    <label for="upsell">Also sign me up for <cite>The CSS3 Chronicle</cite></label>
    <input type="checkbox" id="upsell" name="upsell">
    <input type="submit" id="register-submit" value="Send Post Haste">

For improved accessibility, whenever the required attribute is included, add the ARIA attribute aria-required="true". Many screen readers lack support for the new HTML5 attributes, but many do have support for WAI-ARIA roles, so there’s a chance that adding this role could let a user know that the field is required

Figure 1, Figure 2, and Figure 3 show the behavior of the required attribute when you attempt to submit the form.

Figure 1. The required field validation message in Firefox 4

Figure 1. The required field validation message in Firefox 4

Figure 2. The required field validation message in Opera

Figure 2. The required field validation message in Opera

Figure 3. The required field validation message in Google Chrome

Figure 3. The required field validation message in Google Chrome

Styling Required Form Fields

You can style required form elements with the :required pseudo-class. You can also style valid or invalid fields with the :valid and :invalid pseudo-classes. With these pseudo-classes and a little CSS magic, you can provide visual cues to sighted users indicating which fields are required, and also give feedback for successful data entry:

input:required {
  background-image: url('../images/required.png');
input:focus:invalid { 
  background-image: url('../images/invalid.png');
input:focus:valid { 
  background-image: url('../images/valid.png');

We’re adding a background image (an asterisk) to required form fields. We’ve also added separate background images to valid and invalid fields. The change is only apparent when the form element has focus, to keep the form from looking too cluttered.

Beware Default Styles

Note that Firefox 4 applies its own styles to invalid elements (a red shadow), as shown in Figure 1 earlier. You may want to remove the native drop shadow with the following CSS:

:invalid { box-shadow: none; }

Backwards Compatibility

Older browsers mightn’t support the :required pseudo-class, but you can still provide targeted styles using the attribute selector:

input[required] {
  background-image: url('../images/required.png');

You can also use this attribute as a hook for form validation in browsers without support for HTML5. Your JavaScript code can check for the presence of the required attribute on empty elements, and fail to submit the form if any are found.

The placeholder Attribute

The placeholder attribute allows a short hint to be displayed inside the form element, space permitting, telling the user what data should be entered in that field. The placeholder text disappears when the field gains focus, and reappears on blur if no data was entered. Developers have provided this functionality with JavaScript for years, but in HTML5 the placeholder attribute allows it to happen natively, with no JavaScript required.

  <label for="url">My website is located at:</label>
  <input type="text" id="url" name="url" placeholder="http://example.com">
  <label for="startdate">Please start my subscription on:</label>
  <input type="text" id="startdate" name="startdate" required aria-required="true" placeholder="1911-03-17">

Because support for the placeholder attribute is still restricted to the latest crop of browsers, you shouldn’t rely on it as the only way to inform users of requirements. If your hint exceeds the size of the field, describe the requirements in the input’s title attribute or in text next to the input element.

Currently, Safari, Chrome, Opera, and Firefox 4 support the placeholder attribute.

Polyfilling Support with JavaScript

Like everything else in this tutorial, it won’t hurt nonsupporting browsers to include the placeholder attribute.

As with the required attribute, you can make use of the placeholder attribute and its value to make older browsers behave as if they supported it — all by using a little JavaScript magic.

Here’s how you’d go about it: first, use JavaScript to determine which browsers lack support. Then, in those browsers, use a function that creates a “faux” placeholder. The function needs to determine which form fields contain the placeholder attribute, then temporarily grab that attribute’s content and put it in the value attribute.

Then you need to set up two event handlers: one to clear the field’s value on focus, and another to replace the placeholder value on blur if the form control’s value is still null or an empty string. If you do use this trick, make sure that the value of your placeholder attribute isn’t one that users might actually enter, and remember to clear the faux placeholder when the form is submitted. Otherwise, you’ll have lots of “(XXX) XXX-XXXX” submissions!

Let’s look at a sample JavaScript snippet (using the jQuery JavaScript library for brevity) to progressively enhance our form elements using the placeholder attribute.


In the code examples that follow, and throughout the rest of the book, we’ll be using the jQuery JavaScript library. While all the effects we’ll be adding could be accomplished with plain JavaScript, we find that jQuery code is generally more readable; thus, it helps to illustrate what we want to focus on—the HTML5 APIs—rather than spending time explaining a lot of hairy JavaScript.

Here’s our placeholder polyfill:

if(!Modernizr.input.placeholder) {

  $("input[placeholder], textarea[placeholder]").each(function() {
        if($(this).val()==$(this).attr("placeholder")) {

    // first do all the checking for required 
    // element and form validation. 
    // Only remove placeholders before final submission
    var placeheld = $(this).find('[placeholder]');
    for(var i=0; i<placeheld.length; i++){
      if($(placeheld[i]).val() == $(placeheld[i]).attr('placeholder')) {
        // if not required, set value to empty before submitting

The first point to note about this script is that we’re using the Modernizr JavaScript library to detect support for the placeholder attribute. There’s more information about Modernizr on Sitepoint, but for now it’s enough to understand that it provides you with a whole raft of true or false properties for the presence of given HTML5 and CSS3 features in the browser. In this case, the property we’re using is fairly self-explanatory. Modernizr.input.placeholder will be true if the browser supports placeholder, and false if it doesn’t.

If we’ve determined that placeholder support is absent, we grab all the input and textarea elements on the page with a placeholder attribute. For each of them, we check that the value isn’t empty, then replace that value with the value of the placeholder attribute. In the process, we add the placeholder class to the element, so you can lighten the color of the font in your CSS, or otherwise make it look more like a native placeholder. When the user focuses on the input with the faux placeholder, the script clears the value and removes the class. When the user removes focus, the script checks to see if there is a value. If not, we add the placeholder text and class back in.

This is a great example of an HTML5 polyfill: we use JavaScript to provide support only for those browsers that lack native support, and we do it by leveraging the HTML5 elements and attributes already in place, rather than resorting to additional classes or hardcoded values in our JavaScript.

The pattern Attribute

The pattern attribute enables you to provide a regular expression that the user’s input must match in order to be considered valid. For any input where the user can enter free-form text, you can limit what syntax is acceptable with the pattern attribute.

The regular expression language used in patterns is the same Perl-based regular expression syntax as JavaScript, except that the pattern attribute must match the entire value, not just a subset. When including a pattern, you should always indicate to users what is the expected (and required) pattern. Since browsers currently show the value of the title attribute on hover like a tooltip, include pattern instructions that are more detailed than placeholder text, and which form a coherent statement.

The Skinny on Regular Expressions

Regular expressions are a feature of most programming languages that allow developers to specify patterns of characters and check to see if a given string matches the pattern. Regular expressions are famously indecipherable to the uninitiated. For instance, one possible regular expression to check if a string is formatted as an email address looks like this:


A full tutorial on the syntax of regular expressions is beyond the scope of this tutorial, but there are plenty of great resources and tutorials available online if you’d like to learn. Alternatively, you can search the Web or ask around on the Sitepoint forum for a pattern that will serve your purposes.

For a simple example, let’s add a pattern attribute to the password field in our form. We want to enforce the requirement that the password be at least six characters long, with no spaces:

  <label for="password">I would like my password to be:</label>
  <p>(at least 6 characters, no spaces)</p>
  <input type="password" id="password" name="password" required pattern="\S{6,}">

\S refers to “any nonwhitespace character,” and {6,} means “at least six times.” If you wanted to stipulate the maximum amount of characters, the syntax would be, for example, \S{6,10} for between six and ten characters.

As with the required attribute, the pattern attribute will prevent the form being submitted if the pattern isn’t matched, and will provide an error message.

If your pattern is not a valid regular expression, it will be ignored for the purposes of validation. Note also that similar to the placeholder and required attributes, you can use the value of this attribute to provide the basis for your JavaScript validation code for nonsupporting browsers.

The disabled Attribute

The Boolean disabled attribute has been around longer than HTML5, but it has been expanded on, to a degree. It can be used with any form control except the new output element—and unlike previous versions of HTML, HTML5 allows you to set the disabled attribute on a fieldset and have it apply to all the form elements contained in that fieldset.

Generally, form elements with the disabled attribute have the content grayed out in the browser—the text is lighter than the color of values in enabled form controls. Browsers will prohibit the user from focusing on a form control that has the disabled attribute set. This attribute is often used to disable the submit button until all fields are correctly filled out, for example.

You can employ the :disabled pseudo-class in your CSS to style disabled form controls.

Form controls with the disabled attribute aren’t submitted along with the form; so their values will be inaccessible to your form processing code on the server side. If you want a value that users are unable to edit, but can still see and submit, use the readonly attribute.

The readonly Attribute

The readonly attribute is similar to the disabled attribute: it makes it impossible for the user to edit the form field. Unlike disabled, however, the field can receive focus, and its value is submitted with the form.

In a comments form, we may want to include the URL of the current page or the title of the article that is being commented on, letting the user know that we are collecting this data without allowing them to change it:

<label for="about">Article Title</label>
<input type="text" name="about" id="about" readonly>

The multiple Attribute

The multiple attribute, if present, indicates that multiple values can be entered in a form control. While it has been available in previous versions of HTML, it only applied to the select element. In HTML5, it can be added to email and file input types as well. If present, the user can select more than one file, or include several comma-separated email addresses.

At the time of writing, multiple file input is only supported in Chrome, Opera, and Firefox.

Spaces or Commas?

You may notice that the iOS touch keyboard for email inputs includes a space. Of course, spaces aren’t permitted in email addresses, but some browsers allow you to separate multiple emails with spaces. Firefox 4 and Opera both support multiple emails separated with either commas or spaces. WebKit has no support for the space separator, even though the space is included in the touch keyboard.

Soon, all browsers will allow extra whitespace. This is how most users will likely enter the data; plus, this allowance has recently been added to the specification.

The form Attribute

Not to be confused with the form element, the form attribute in HTML5 allows you to associate form elements with forms in which they’re not nested. This means you can now associate a fieldset or form control with any other form in the document. The form attribute takes as its value the id of the form element with which the fieldset or control should be associated.

If the attribute is omitted, the control will only be submitted with the form in which it’s nested.

The autocomplete Attribute

The autocomplete attribute specifies whether the form, or a form control, should have autocomplete functionality. For most form fields, this will be a drop-down that appears when the user begins typing. For password fields, it’s the ability to save the password in the browser. Support for this attribute has been present in browsers for years, though it was never in the specification until HTML5.

By default, autocomplete is on. You may have noticed this the last time you filled out a form. In order to disable it, use autocomplete="off". This is a good idea for sensitive information, such as a credit card number, or information that will never need to be reused, like a CAPTCHA.

Autocompletion is also controlled by the browser. The user will have to turn on the autocomplete functionality in their browser for it to work at all; however, setting the autocomplete attribute to off overrides this preference.

The datalist Element and the list Attribute

Datalists are currently only supported in Firefox and Opera, but they are very cool. They fulfill a common requirement: a text field with a set of predefined autocomplete options. Unlike the select element, the user can enter whatever data they like, but they’ll be presented with a set of suggested options in a drop-down as they type.

The datalist element, much like select, is a list of options, with each one placed in an option element. You then associate the datalist with an input using the list attribute on the input. The list attribute takes as its value the id attribute of the datalist you want to associate with the input. One datalist can be associated with several input fields.

Here’s what this would look like in practice:

<label for="favcolor">Favorite Color</label>
<input type="text" list="colors" id="favcolor" name="favcolor">

<datalist id="colors">
  <option value="Blue">
  <option value="Green">
  <option value="Pink">
  <option value="Purple">

In supporting browsers, this will display a simple text field that drops down a list of suggested answers when focused. Figure 4 shows what this looks like.

Figure 4. The datalist element in action in Firefox

Figure 4. The datalist element in action in Firefox

The autofocus Attribute

The Boolean autofocus attribute specifies that a form control should be focused as soon as the page loads. Only one form element can have autofocus in a given page.

For the next article in this series, visit Better web forms with HTML, Part 3

This is an excerpt from HTML5 & CSS3 for the Real World, by Alexis Goldstein, Louis Lazaris & Estelle Weyl.