November 2011

Volume 26 Number 11

Building HTML5 Applications - Better Web Forms with HTML5 Forms

By Brandon Satrom | November 2011

If you’re a Web developer, you’ve probably created an HTML Form before. In fact, you may have created more of them than you care to remember. You’re no doubt familiar with classic input types like text, password, file, hidden, checkbox, radio, submit and button, and you’ve probably used most or all of these at various times.

If I were to ask you what type of input—from the previous list—you use more than any other, you’d probably say “text,” as would most of us. The text input type is the multitool of classic HTML Forms development. On the one hand, it’s able to adapt to nearly any job you give it, but on the other, it’s semantically neutral, so the browser offers no help in turning this element into something practical. To compensate, developers and designers have added their own semantics to these elements (via IDs and class names) and have relied on server frameworks and JavaScript to handle validation and add rich interactions.

A classic example is collecting dates in text fields. Most of the time, you want to enhance a date field with a date picker of some kind. This is often done with hand-rolled JavaScript or a framework like jQuery UI, which adds an interaction behavior that allows the user to select a date from a widget and have that date populated into the original field.

As useful as that pattern is—and we’ve become quite adept as developers with patterns like this—it’s repeated so often that you can’t help but ask, “Why can’t the browser just do it?”

The good news is that, with HTML5 Forms, the browser can—and will. In addition to text and the handful of existing types we’ve had for years, HTML5 adds 13 new values for the input type attribute, as well as a host of other attributes that will speed up your forms development. This month, I’ll share some of the new input types and attributes coming with HTML5 Forms, as well as their implementation status in various browsers. Next, I’ll present a quick overview of new client validation features for HTML5 Forms. 
Finally, I’ll take a look at how recent updates to Visual Studio 2010 and the Microsoft .NET Framework 4 enable HTML5 Forms and ASP.NET Web Forms to play well together. Throughout, I’ll discuss how you can embrace HTML5 Forms in your applications today, while providing fallback solutions for older browsers. All of the demos for this article—which are available online—were built using WebMatrix, a free, lightweight Web development tool from Microsoft. You can try WebMatrix out for yourself at aka.ms/webm.

New Input Types in HTML5

What we know today as HTML5 Forms or HTML5 Web Forms started as Web Forms 2.0, a pre-HTML5 specification authored by a group known as the Web Hypertext Applications Technology Working Group, or WHATWG. Much of the initial work by WHATWG became the starting point for what we now call HTML5, and the Web Forms 2.0 effort is now part of the official HTML5 specification, which you can read at bit.ly/njrWvZ. A significant portion of the specification is dedicated to new types and content attributes for the input element, which you’ll find at https://www.w3.org/TR/2011/WD-html5-20110525/common-input-element-attributes.html.

As I mentioned, the specification introduces 13 new input types for use in forms: search, tel, url, email, datetime, date, month, week, time, datetime-local, number, range, color.

Using these new types is simple. Say I want to put a new e-mail field on an order form. As you can see in Figure 1, I’ve modified the WebMatrix Bakery Template Web site’s Order page with some additional fields, including e-mail.

A Sample Order Form
Figure 1 A Sample Order Form

For this form, the e-mail field is marked up like so:

<input type="email" id="orderEmail" />

Notice that the type attribute is equal to “email” instead of “text.” The best part about the new HTML input types is that you can use them today and they work, at some level, in every single browser. When a browser encounters one of these new types, one of two things will happen.

If the browser doesn’t support the new input types, the type declaration won’t be recognized. In this case, the browser will gracefully degrade and treat the element as type=“text.” You can try this by putting this element on a form and typing “document.getElementById(‘orderEmail’).type” in the Internet Explorer 9 F12 Tools Console. So, you can use these new types today, and if the browser doesn’t support a given field, it will continue to work just like a regular text field.

If the browser does recognize a type, however, you’ll gain some immediate benefits by using it. For recognized types, the browser adds some type-specific built-in behavior. In the case of the email type, Internet Explorer 10 Platform Preview 2 (PP2) and later will automatically validate any input, and present the user with an error message if the provided value isn’t a valid e-mail address, as shown in Figure 2.

Automatic Browser Validation of the Email Input Type
Figure 2 Automatic Browser Validation of the Email Input Type

It’s easy to infer the purpose and behavior of each element by its type, so we readily gain another level of semantic richness in our forms. Moreover, some of these new input types let the browser provide richer interactions to users out of the box. For example, if I place the following element on a form and then open that form in a browser that fully supports the date input type, the default interaction is much richer than a plain old text box:

<input type="date" id="deliveryDate" />

Figure 3 shows what the date type can provide in Opera 11.5. The best part is that all I had to do to get this interaction was specify type=“date” and the browser took care of all the manual work I previously had to do in JavaScript to offer this level of functionality.

The Date Input Type in Opera 11.5
Figure 3 The Date Input Type in Opera 11.5

It’s important to note that the HTML5 specification doesn’t dictate how browsers should present these new input types, or how they should present validation errors, so you can expect to see subtle to major differences among browsers. For example, Chrome 13 presents a spinner control for the date rather than a date picker, as shown in Figure 4 (which, of course, may have changed by the time you read this). You should also know that there’s ongoing discussion in the World Wide Web Consortium, or W3C, around browser styling and localization of elements like datetime, date and color. The browsers don’t all agree, at present, on how to implement these types, and there’s no current customization mechanism within 
existing implementations that’s similar to what you’d find with jQuery UI. Should you choose to implement or experiment with these new types, always be sure to provide a thorough fallback solution. In addition, if consistency of presentation and behavior is important to your users, you may need to apply custom styles, override default behaviors on these controls or use a script-based solution.

The Date Input Type in Chrome 13
Figure 4 The Date Input Type in Chrome 13

Earlier I stated that these fields will still behave as regular text fields, which is a nice piece of graceful degradation the browsers provide for us. But a date field implemented as a plain text box is clunky, and widely considered a poor user experience. With a little help from Modernizr and jQuery UI, however, you can provide a solution that mixes the best of HTML5 Forms with a nice fallback solution.

You’ll recall from my last article (msdn.microsoft.com/magazine/hh394148) that Modernizr (modernizr.com) is a JavaScript library that can help you detect support for HTML5 features in the browser. For this example, I want to use Modernizr to help detect support for the HTML5 date input type and, if it’s not supported, use the jQuery UI (jqueryui.com) datepicker widget to provide a similar user experience. Once I’ve downloaded and added references for Modernizr, jQuery and jQuery UI, I can add fallback support for my date elements with just a few lines of code:

if (!Modernizr.inputtypes.date) {
  $("input[type=date]").datepicker();
}

The result, as seen in Internet Explorer 10 PP2, is depicted in Figure 5.

Date Field Support with jQuery UI
Figure 5 Date Field Support with jQuery UI

New Input Content Attributes in HTML5

In addition to the new input types, HTML5 provides some handy new content attributes that can be used on input fields to supply validation support and enhanced functionality. One of those new attributes is “placeholder,” which, according to the specification, “…represents a short hint (a word or short phrase) intended to aid the user with data entry” (emphasis theirs). For example, I can take a couple of the fields from our order form and add placeholder=“some text” to each field, with the result shown in Figure 6:

<input type="email" id="orderEmail" placeholder="ex. name@domain.com" />
<input type="url" id="orderWebsite" placeholder="ex. https://www.domain.com" />

Using the Placeholder Attribute with Input Fields
Figure 6 Using the Placeholder Attribute with Input Fields

The placeholder text is lighter in color than normal text, and if I place focus on each field, the text disappears, enabling me to 
enter my own value.

As with the new input types, the placeholder attribute isn’t supported in older browsers. Nothing bad will happen if a user visits a page with them, though, so consider using them today, even if you don’t plan to add support for older browsers. If you do want to “polyfill” placeholder support, Modernizr can help. As I mentioned in my last article, the good folks at Modernizr try to keep a running list of every polyfill and fallback you could possibly want for a given HTML5 feature. You can check that list out at bit.ly/nZW85d.

For this example, let’s use the jQuery HTML5 Placeholder created by Mike Taylor, which you can download from bit.ly/pp9V4s. Once you have it, add the following to a script block referenced by your page:

Modernizr.load({
    test: Modernizr.input.placeholder,
    nope: "../js/html5placeholder.jquery.min.js",
    callback: function() {
      $('input[placeholder]').placeholder();
    }
  });

Here, Modernizr tests whether the placeholder attribute is supported and if it’s not, loads html5placeholder.jquery.min.js. jQuery then selects every element with a placeholder attribute and adds plug-in support to each. If you try this out in Internet Explorer 9, you’ll notice that the end result looks very similar to the native browser support provided in Internet Explorer 10 PP2.

Another interesting new attribute is “autofocus,” which, as it sounds, lets you specify a single form field to automatically receive focus when a page loads. Only one field per page should hold this attribute; if multiple elements are marked up with autofocus, the first one with that declaration receives focus on page load. For my order form, I want the Name field to receive focus, so I add the attribute like so:

<input type="text" class="field" id="orderName" autofocus />

The autofocus attribute can be used on any form control, and is an excellent alternative to the script-based, form-focused strategies many Web developers have fought with in the past.

HTML5 Form Validation

I don’t have the space to cover all the interesting new form-related attributes here, but I’ll spend a few moments talking about “required,” “pattern,” “novalidate” and “formnovalidate,” all of which make client-side form validation a snap.

For browsers that support it, the “required” attribute tells the browser that this form can’t be submitted without a value. For example, I add “required” to the Name field of my order form:

<input type="text" class="field" id="orderName" required />

When I visit this page in the Internet Explorer 10 PP2 and attempt to submit the form, I see something like what’s shown in Figure 7. With a single attribute, the browser knows enough to style the element with a red border and display a message to the user indicating that the field is required.

Using the Required Attribute on a Form Field
Figure 7 Using the Required Attribute on a Form Field

Earlier, Figure 2 showed how the browser can automatically validate certain types, such as “email” and “url,” without additional input from the user. With the “pattern” attribute, you can provide your own validation test for input types. According to the HTML5 specification, “pattern” expects a regular expression, which the browser uses to validate the owning field.

My order form contains a telephone (type=“tel”) field and I can specify a validation pattern like this:

<input type="tel" id="orderTelephone" pattern="\(\d\d\d\) \d\d\d\-\d\d\d\d" title="(xxx) xxx-xxxx" />

This (not very complex) regular expression tells the browser to expect a seven-digit number with parentheses around the area code and a dash in the local number. Entering anything else results in the message shown in Figure 8. Notice that the message contains instructions to the user on how to format input: “(xxx) xxx-xxxx.” This part of the message is taken from the title attribute of the same element, so it’s possible to control at least part of the validation message via your markup. There’s one thing to note when using title to aid in validation, though. According to the spec, the browser may choose to show the title in other, non-error cases, so don’t count on this attribute as a place for error-sounding text.

Using the Pattern Attribute to Specify a Validation Expression
Figure 8 Using the Pattern Attribute to Specify a Validation Expression

Automating validation by the browser is nice, but two immediate questions come to mind. First, what about server validation or client validation scripts generated by my server framework (ASP.NET MVC, for example)? And second, what about cases where I want the user to be able to save the form as a work in progress, without validation? The first is, unfortunately, outside the scope of this article, but I’ve written a blog post about this very subject in ASP.NET MVC, which you can find at bit.ly/HTML5FormsAndMVC.

The second question, on the other hand, is easy. Let’s assume you have a form that users will spend quite a bit of time on before submitting, perhaps even saving multiple times before finally posting it to your server. For such cases, where you’ll want to allow a user to submit a form without validation, there are two attributes you can use: “formnovalidate,” which is placed on input fields of type “submit,” and “novalidate,” which is placed on an opening form tag. Here I’ll place two submit fields on my form, like so:

<input type="submit" value="Place Order" />
<input type="submit" formnovalidate value="Save for Later" id="saveForLater" />

The “formnovalidate” attribute on the second button will turn off validation and submit the form, allowing the user’s work in progress to be saved in my database, or even on the client side using a new HTML5 storage technology like localStorage or IndexedDB.

HTML5 Forms and ASP.NET Web Forms

Before I wrap up this article, I want to share a few additional bits of information related to HTML5 Forms for ASP.NET Web Forms developers. If you’re planning to do HTML5 Forms development with ASP.NET Web Forms, there’s good news: Many HTML5-related updates to .NET and Visual Studio are being released out-of-band, so you don’t have to wait for the next framework version to use these features today.

To get started with HTML5 Forms and ASP.NET Web Forms, you’ll need to grab a couple of updates. First, make sure you have Visual Studio 2010 SP1 (bit.ly/nQzsld). In addition to adding support for new HTML5 input types and attributes, the service pack also provides some updates that enable you to use the new HTML5 input types on the TextBox server control. Without this update, you’d see compile-time errors when using the new types.

You’ll also want to grab the Microsoft .NET Framework 4 Reliability Update 1 (bit.ly/qOG7Ni). This update is designed to fix a handful of problems related to using the new HTML5 input types with ASP.NET Web Forms. Scott Hunter covers a few of those—UpdatePanel, Validation Controls and Callbacks—in a blog post from early August that you can check out at bit.ly/qE7jLz.

The addition of Web Forms support to browsers with HTML5 is good news for Web developers everywhere. Not only do we have a set of semantic input types to leverage in our applications, but we can also use these input types today with no ill effects in older browsers, while getting enhanced functionality—including automatic client validation—in newer ones. Using these new fields right away has immediate benefits in the mobile application space as well, where using types like “url” and “email” will prompt mobile devices to present the user with soft keyboard options tuned for that input type. When you combine these new features with Modernizr and one of the great polyfilling options, you have all the tools you need to adopt HTML5 Forms in your applications right now.

For more information on HTML5 Forms support in Internet Explorer 10 PP2, go to ietestdrive.com, and be sure to check out the developer’s guide at the Internet Explorer Developer Center (bit.ly/r5xKhN). For a deeper dive into HTML5 Forms in general, I recommend “A Form of Madness,” from Mark Pilgrim’s book “HTML5: Up and Running” (O’Reilly Media, 2010), as well as the Forms section of the W3C HTML5 specification (bit.ly/nIKxfE).     


Brandon Satrom*works as a developer evangelist for Microsoft outside of Austin, Texas. He blogs at userinexperience.com and can be found on Twitter as @BrandonSatrom.*

Thanks to the following technical experts for reviewing this article: *Jon BoxJohn HrvatinScott Hunter and *Clark Sell