RELATED: "How to Structure JavaScript Code, Part 1" and "Introduction to HTML5 for Mobile App Development." 

Writing software is, for the most part, a creative job. Of course, we developers well know that not all the software we write is the fruit of our creativity. Sometimes we have no other option than to write the same boilerplate code for the umpteenth time. A great example of boilerplate code we'd love to no longer have to write is code to handle validation of input forms in HTML pages. An HTML input form displayed through the web browser is expected to collect data that the server application will process. Some validation rules are likely business specific and can be applied only on the server. At the same time, though, certain basic validation tasks can be easily delegated to the browser and commanded by developers using markup instead of JavaScript code.

HTML5 brings a number of changes in this area and addresses many scenarios that would reduce the amount of boilerplate code needed to build effective input forms. By using the entire set of attributes of the HTML5 <input> element, you can say goodbye to jQuery and its ad hoc plug-ins, at least for basic tasks such as ensuring that a field isn't left blank and checking the type of data being entered. In this article, I'll discuss core features common to all input fields and the tools HTML5 gives you to control the process of form validation. In upcoming articles, I'll cover new and more specific types of input fields, such as numeric and date fields.

Dealing with Required Fields

Nearly any form displayed through a web browser has at least one required field. A required field is expected to have a value entered in it before the form containing the field can be safely submitted to the server for further processing. Prior to HTML5, this task could be easily accomplished using some JavaScript code, as shown in the example in Listing 1.

<script type="text/javascript">
    $(document).ready(function () {
        $("#submitButton").click(function () {
            if (!$("#yourpin").val()) {
                alert("Enter your PIN to proceed!");
            }
        });
    });
</script>

The code snippet in Listing 1 assumes a web page with an HTML form that's defined as follows:

                              <form>                                  <input id="yourpin">                                  <input id="submitButton" type="submit" value="Connect">                              </form>

Even though the required-field validation code is short and simple, repeating it over and over again for each input field could become an annoying task. Using a specialized plug-in such as jQuery Validation is mostly a palliative remedy that doesn't really solve the problem. However, checking that a given field isn't left blank on a form doesn't require knowledge of the business context and can be done more effectively at the markup level. This is just what HTML5 allows you to do with the new required attribute. Here's how to rewrite the previous sample page in HTML5 using the required attribute.

                              <form>                                  <input id="yourpin" required>                                  <input id="submitButton" type="submit" value="Connect">                              </form>

An HTML5-compliant browser is all you need; no scripts and no additional libraries are necessary. Note that in HTML5, XML syntax compliance is no longer required; thus you're no longer forced to assign a value to the required attribute. All that matters is that the attribute is found in the element. The following markup is also acceptable:

<input id="yourpin" required="required">

Understandably, support for HTML5 isn't yet uniform across browsers. The latest versions of all major browsers -- Internet Explorer (IE), Chrome, Firefox, Safari, and Opera -- offer superb support for HTML5, but if you happen to use an older version (even a few months older), you might run into trouble. As far as the required attribute is concerned, you won't find it supported in IE (until version 10) and Safari. On other browsers, the required attribute has long been supported, and backward compatibility is probably isn't a big concern.

Giving Users Feedback on Required Fields

Checking whether a required field is left blank is only half of the problem. What do you want to do once an input field is unexpectedly found blank? Should the browser simply block form submission? Should the browser display a generic error message about the entire form? Or, instead, should the browser display a field-specific error message?

Generally, browsers display a per-field feedback when a required field is left empty. Figure 1 shows the field-input tooltip that each of three browsers -- Chrome, Firefox, and Opera -- currently provides.

Figure 1: How Chrome, Firefox, and Opera Treat Blank Required Fields

As you can see, each browser displays a different message. Should you accept the default browser behavior or try to customize it to some extent? As I see it, there are good reasons for taking either approach.

The advantage of leaving the look and feel and content of the standard tooltip unchanged is that this ensures that users will always receive the same feedback when they leave a field blank on any site they visit. The advantage of customizing the tooltip -- and specifically the error message -- is that doing so gives the user more context about why the field is required. Which approach you take depends on the user experience (UX) you want for the application. Although I'm not a UX expert, as a user I'd love to receive a "friendly" message instead of an aseptic error message.

However, let's assume that UX experts at browser companies have probably figured out a good-enough default behavior; you can change it, but you'd better have a compelling reason to do so. So how can you modify the error message?

Customizing the Error Message

According to the new HTML5 Document Object Model (DOM), the error message that's displayed for blank required fields can be controlled programmatically using the setCustomValidity method that's exposed by input elements, as shown in the following example code. (See the WHATWG's HTML standard documentation for more information.)

<input id="yourname" required
    oninvalid="this.setCustomValidity
      ('User name is mandatory')" />

You write a handler for the new oninvalid event and pass the setCustomValidity method the string to display. This approach works with all browsers and is the official way of achieving this task. If you're looking for a full markup solution, be prepared to devise different tricks for different browsers.

By setting the title attribute to a non-empty string, you instruct the Chrome browser to add a second line to the tooltip with just the specified message. Firefox, instead, offers the custom x-moz-errormessage attribute to replace the default text:

<input id="yourname" required
    x-moz-errormessage="User name is required to proceed." />

If specified, a call to setCustomValidity made during the oninvalid event takes precedence over browser-specific attributes; Figure 2 shows the results. Note that Opera allows you to customize the error message only through the setCustomValidity method.

Figure 2: Customizing the Required-Field Error Message on Different Browsers

Styling Required Fields

HTML5 also brings a bunch of new Cascading Style Sheets (CSS) predefined classes for you to style. In particular, you have the valid and invalid classes to style input fields accordingly. Listing 2 shows a simple example of using the new classes. In this way, the specified style is automatically applied to any required input fields when the browser reckons their status valid or invalid.

<style>
        input {
            border: solid 1px #000;
        }
        input:required:invalid  {
            background-color: red;
       }
        input:required:valid  {
            background-color: green;
       }
</style>

Needless to say, you can also use other CSS classes to achieve more sophisticated effects. For example, by changing the background image of the input field, you can give immediate feedback to the user through a nice bitmap image, as shown in Listing 3.

<style>
        input {
            border: solid 1px #000;
        }
        input:required:invalid  {
            background-image: url(/images/invalid.png);
            background-position: right;
            background-repeat: no-repeat;
       }
        input:required:valid  {
            background-image: url(/images/valid.png);
            background-position: right;
            background-repeat: no-repeat;
       }
</style>

Preventing Form Validation

HTML5 doesn't require that browsers validate the content of a form being submitted. This is what happens by default, though, and it's indeed a reasonable default behavior. HTML5 form validation entails checking that each input field in the form contains valid content. The first control in the page that fails in showing valid content is set to the invalid state and refreshed, according to current CSS styling. In addition, the tooltip with error message is displayed.

If you use validatable attributes in an input field (e.g., required), you can't skip validation on that field. As I plan to discuss in upcoming articles, the required attribute is just one of the validation-related attributes in HTML5. Data-specific input fields (for date, time, numbers, and more) are other relevant examples of input fields that could require browser validation.

In HTML5, a browser's form validation is enabled by default and can be disabled on the entire form -- not on individual fields. You disable form validation by using the novalidate attribute, as follows:

<form novalidate>
   :
</form>

It should be noted that when novalidate is used, tooltips for invalid fields aren't displayed, but CSS classes are honored anyway. With reference to Figure 3, this means that in case of no validation, you won't get the tooltip, but the style of input fields will be changed as shown.

Figure 3: Styling Required Input Fields Using CSS

When the input form contains multiple submit buttons, you might want browser-side validation for some buttons but not for all of them. If, for example, one of the submit buttons isn't expected to use any of the input data, there's no value in performing client-side validation. HTML5 also provides an ad hoc attribute to handle such a situation:

<input type="submit" value="..." formnovalidate />

The formnovalidate attribute tells the browser to skip form validation if the form is being posted through that particular button. HTML5 browsers ignore the formnovalidate attribute if it's used with anything other than submit buttons. Note also that the formnovalidate attribute overrides the form's novalidate attribute if both are present.

Easier Validation

With HTML5, the focus is often on aspects of HTML5 that represent side programming frameworks, such as local storage, web sockets, and geolocation. But HTML5 is also important to developers because it delivers a much better and richer markup language, providing new tags such as datalist, details, and video as well as semantic tags. HTML5's markup language improvements allow developers to perform web programming tasks more easily -- most notably, input form validation and processing of required fields, which we'll explore further in "HTML5 Form Input Enhancements: Form Validation, CSS3, and JavaScript." The major problem with HTML5 that developers face today is dealing with older browser versions that don't support HTML5. With help from tools such as Modernizr, which offers a unified and cross-browser API for HTML5 development, you can circumvent browser-compatibility obstacles and take advantage of HTML5's form-validation efficiencies.