imageValidate, validate, validate. Whenever a user needs to submit data to your application, you need to validate users input.

And what if you could design your form without any JavaScript at all, and add validation later, and thereby improving the user experience (UX) as much as possible. jQuery and certain frameworks help  a lot with this, due to its unobtrusive nature.

This means you can write your HTML and then add the validation at a later time.

In this post, I’ll show how you can do validation out of the box with HTML5. And I’ll show how you can use frameworks to ease the burden of backward compatibility and even make it easier to display errors. I’ll show how you can write business rules to validate your user’s input.

Validation Pattern

The idea is that you can design your HTML and then design the JavaScript for your business logic and validation. When you later change your user experience in HTML, you can also update your JavaScript.

Although HTML5 has some built in functionality, you will want to provide additional rules to your client side input. And let’s also remember that you can use these same validation code when you run JavaScript on the server.

Check user input. And if you can, check it on the client to avoid unnecessary round trips. And of course, check it on the server side too. You probably will not try to catch every thing on the client side. Some of the more complex validation can still run on the server. After all, you do not want bloated code running in your browser, nor do you want super complex code signaling errors that are not errors because you are trying to handle weird combinations of user input.

You can use a small validation framework that can do most of the validation. And that is the topic of this post.

NOTE: Just because you check the data on the client, does not mean you should ignore error checking on the server. Be sure to check data coming in. Client-side validation provides a better user experience and helps keep bandwidth down from sending and receiving bad data.

Reformat Data

You may also want to make your HTML5 application more friendly. Imagine a situation where the user would like to enter information in different ways, that would satisfy your user input and still provide data in the format you need. Typical areas where reformatting can be used:

  • Dates
  • Time
  • Phone numbers
  • Social Security numbers / Personal Numbers
  • Trim spaces
  • Remove/exchange invalid characters

Internationalization (I18N)

If your web is successful for an international public, the non-English-speaking audience is next. In order to achieve this it is important that even user generated error messages is localized and translated. Make sure your client side validation framework is prepared for translation and other localized parameters such as currencies, dates and time-formatting.

Choose a Framework

Of course you can write your own validation framework.

You can use the HTML5 tags and attributes to do simple validation.

You can use a framework like jQuery Validation or Webshims to help.

Test Your Framework

There is one thing worse than no validation: Validation can incorrectly stop correct data from getting through. In order to avoid this, coding is a smaller part then the actual testing of the validation framework.

Make sure the validation does what you think it should be doing.

Getting Started with Validation

HTML5 supports validation within the tags itself. And it supports an API.

New HTML5 Forms support includes:

  • Support for the Search, Telephone, URL, Email, and Numberinput states. Input for URL and Email will only accept properly formatted URLs and email addresses.
    <input type="url" name="url"/>
    <input type="email" name="email"/>
  • Support for the Range input state, which enables the creation of a range or slider input control. This input state, which is signaled by setting the type attribute to "range", also includes the min, max, step, and valueattributes, which define the value range and resolution of the control.
    <input type="range" min="0" max="100" step="5" value="50"/>
  • Support for new HTML input attributes, which help ensure that required data is entered, and that data is entered correctly:
  • Support for custom validation error messages, which enable you to indicate to users how to properly format entries such as telephone numbers or email addresses.
  • Support for custom validation error messages, which enable you to indicate to users how to properly format entries such as telephone numbers or email addresses.
  • Automatic Caps Lock warning on password fields.
  • Support for the CSS pseudo-classes :valid and :invalid, which enable you to style a field according to whether its contents are valid.
  • Support for the constraint validation APIfrom the W3C. So you can do some validation an use that looks like this:
    var arrivalDate = document.getElementById("arrivalDate");
    arrivalDate.addEventListener("input", function () {
        var value = new Date(arrivalDate.value);
        if (value < new Date()) {
            arrivalDate.setCustomValidity("Arrival date must be after now!");
        } else {
            arrivalDate.setCustomValidity("");
        }
    });
    which  displays this when the input is before today.
    image

How Frameworks Help

You may want to choose a framework with validation. The frameworks provide backward compatibility for older browsers:

  • A way to go beyond what is in HTML5 to include basic business rules for the input.
  • Provide support for browsers that do not have full HTML5 support. In other words, not all browsers will do the right thing when it encounters an input that does not match a pattern tag, as an example.

But none of the frameworks do the whole job. There does not seem to be a plug-in, shim, nor polyfill that provides support for both both the required and pattern attributes for older browsers, but does not get in the way of these attributes in the case of newer browsers.

So you will need to compromise. You’ll need to choose your framework based on the features you will want your HTML5 to support.

I’ll show off some, but not all, of the features in several plugins with the eye around how they would support patterns, required attribute, error message display, and custom validation.

Stephen Walther provides a great blog post that includes code on many of the plugins and how they are supported. See HTML5 Form Validation.

I’ll add some examples and call out some of his.

Webshims Lib

In a previous post, I showed how you can use some basic validation without code using Webshims Lib. It isn’t specifically a validation framework really. But does provide constraint validation and input widgets that work well in HTML5 and provides polyfill where the modern inputs can work in older browsers that do not support HTML5.

The forms (constraint validation without number, date etc.) and forms-ext (number, date, range etc.) features of Webshim Lib support the constraint validation API that I mentioned in a previous section. It also supports some input widgets and the placeholder-attribute.

And showed how you can use a polyfill for the UI to remain consistent across browsers. It checked input attributes used in HTML5. I showed how Webshims supports:

  • max. Specifies the maximum value for an <input> element.
  • min. Specifies a minimum value for an <input> element.
  • pattern. Specifies a regular expression that an <input> element's value is checked against.
  • required. Specifies that an input field must be filled out before submitting the form.
  • size. Specifies the width, in characters, of an <input> element.
  • step: Specifies the legal number intervals for an input field.

You can also customize error messages and create custom validation rules.

Patterns with Webshims

For example, you can use patterns to do validation. For example, you can check a part number using a regular expression to define the rule in a pattern attribute:

<input pattern="[0-9][A-Z]{3}" title="A part number is a digit followed by three uppercase letters." />

OR

<label>Social Security Number: 
    <input required pattern="^\d{3}-\d{2}-\d{4}$"   title="###-##-####" />
</label>

The title is what the browser displays a tool tip when you hover over the input.

image

And Webshims will support the validation across multiple browsers using the native interface.

Custom Rules

There are several ways you can add custom validation constraints with HTML5.

  • pattern attribute (see also html5pattern.com)
  • dynamically changing constraints depending on a value and whether an checkbox input is checked or cleared
  • setCustomValidity

Webshim Lib comes with a simple custom validity helper located in the extras-folder (custom-validity.js). This script is an extension and it works with and without Webshim Lib.

Several helper functions let you:

  • Validate a credit card number
  • Require an item be checked. 'group-required' at least one of the checkboxes with the same name inside the form/document has to be checked.
  • And dependencies which allow you to link one item to another.

For example:

<!-- if checkbox is checked, the field is required -->
<input type="checkbox" id="checkbox" />
<input data-dependent-validation='{"from": "checkbox", "prop": "required"}' />

And you can write your own rule by using $.webshims.addCustomValidityRule whose parameters are name of constraint, test-function, default error message.

$.webshims.addCustomValidityRule('testname', function(elem, value){
    if(value && $(elem).hasClass('test-class') && value != 'foo bar baz'){
        return true; //means yes, it's not valid
    } else {
        return false; //no, it is valid
    }
}, 'you have to enter foo bar baz'); 

Dependency Rules Between Elements

You can declare that the value of one element is dependent on the value of another. For example, the following code requires that the user enter information in the text input if Other is selected in the drop down.

    <div class="form-element">
        <label for="special1">How did you hear about us?
            
        </label>
        <select name="special1" id="special1">
            <option value="magazine">Magazine</option>
            <option value="friend">Friend</option>
            <option value="other">Other (please explain)</option>
        </select>
        <br />
        <label for="special2">
            Other: 
        </label>
        <input data-dependent-validation='{"from": "special1", "prop": "required", "from-prop": "value:other"}'
            name="special2" type="text" id="special2" />
    </div>

Be sure to call Scripts\js-webshim\minified\extras\custom-validity.js

For more information about Custom Rules using Webshims, see Adding new validation constraints/dynamically changing constraints of HTML5 form elements.

How to Get Webshims

Get Webshims Libs from GitHub.

Then copy over the files to your Scripts folder. For you to run the demos from the source code, you will need to copy the files into your Scripts folder:

image

jQuery Validation Plugin

Another way to do validation is the jQuery Validation Plugin.

The jQuery Validation plug in helps you validate your user input using jQuery. It is one of the oldest jQuery plugins and proved itself in projects all around the world. It is offered on the ASP.NET CDN. 

There is also an article discussing how this plugin fits the bill of the should-be validation solution.

  • Required: The typical and probably most used validation out there.
  • Minlength & Maxlength: Staple Length validation rules
  • Rangelength: Similar to Min/Maxlength; allows for selected item counts as well.
  • Min & Max & Range: Same as the "length" rules above only for numeric values.
  • Email: A very robust email validation rule
  • Url: Ensures the input is a well formatted url.
  • Date: Verifies the input can be parsed into a date.
  • Number: Ensures that the input is numeric.
  • Digits: Ensures only 0-9 characters (no commas, decimal points, etc.)
  • Credit Cards: Another complex and common validation rule made easy.
  • Accept: A file extension validation rule.
  • EqualTo: Ensures that the values of 2 elements are the same.

Let’s start with how to get jQuery Validation, then show how to use it to test for required inputs, size, and patterns. We’ll see how to build your own rules in JavaScript.

Next, we’ll see how you can use code to validate multiple fields and validate using simple business rules. And then I’ll show how you can integrate jQuery Validation with WebShim.

How to Get jQuery Validation

You can get the code directly from jQuery plugin: Validation. You will see the latest version there.

OR … If you are using Visual Studio, you can get jQuery Validation from NuGet. Right click your project, click Manage NuGet Projects. You can search for jQuery Validation and install.

image

OR … You can also link directly to jQuery Validation using ASP.NET CDN. For example:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js” type=”text/javascript”></script>

You can get additional methods, localized versions, and the VSDOC, which Visual Studio will use for Intellisense.

Setting Up Validation

Start with your form. Here’s an example form using labels:

<form id="commentForm" method="get" action="#">
 <fieldset>
   <legend>Simple Example</legend>
   <div>
     <label for="nameInput">Name</label>
     <input id="nameInput" name="name" size="25" class="required" minlength="2" />
   </div>
   <div>
     <label for="emailInput">E-Mail</label>
     <input id="emailInput" name="email" size="25"  class="required email" />
   </div>
   <div>
     <label for="urlInput">URL</label>
     <input id="urlInput" name="url" size="25"  class="url" value="" />
   </div>
   <div>
     <label for="comment">Your comment</label>
     <textarea id="comment" name="comment" cols="22"  class="required"></textarea>
   </div>
   <div>
     <input class="submit" type="submit" value="Submit"/>
   </div>
 </fieldset>
 </form>

Note that the form uses class="required" and class for the input types.

Next I can add some styles that will be used to add the warning messages.

<style type="text/css">
    label { width: 10em; float: left; }
    label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
</style>

When jQuery Validation finds an error, it displays the error using the .error style. So my style for label.error in my CSS is used to display the warning. Note how the .error sets the text positioning.

I must also load the plugin, which causes the form to be validated:

<script type="text/javascript">
    $(document).ready(function () {
        $("#commentForm").validate();
    });
</script>

And when you enter some text for a name, and then click Submit, the validation is applied.

image

And then if I type in a partial email and click Submit, I am told that I need an email address.

image

Validation plug-in automatically checks based on the class. It also displays the warnings based on the styles.

You can further customize the style. For example, you can apply this style to .error:

<style type="text/css">
    .error {    
            font: normal 10px arial;    
            padding: 3px;    
            margin: 3px;    
            background-color: #ffc;    
            border: 1px solid #c00;
        }
</style>

And get this:

image

And it does what you expect with the focus. When there is an error, the first invalid element is focused. Also, the user can tab through fields without getting error messages.

Adding Rules and Custom Messages

The advantage of using jQuery Validation plugin is so you can declare validation rules and messages using JavaScript.

The rules and messages are parameters you can pass to the form validation. For example for this element:

<input type="text" name="mycreditcard" id="mycreditcard" size="40" class="required">

(note class="required" is for the styles to display the validation text correctly.)

We can run this script:

    <script type="text/javascript">
        $(document).ready(function () {
            $("form").validate({
                rules: {
                    mycreditcard: {
                        required: true,
                        creditcard: true
                    }
                }
            });
        });
    </script>

Here we define rules parameter of form validate() with the name of the input element. You can then specify that it is required and to validate it using the creditcard validation in jQuery Validation. mycreditcard refers to the name attribute in the inputelement.

You also create custom messages.

Use the same declarative style for remote validation as you are used to use for local validation. String.format creates another function that is later called with the value the user entered, resulting in something like “The name asdf is already in use” as the error message.

$("#myform").validate({
  rules: {
    username: {
      required: true,
      minLength: 2,
      remote: "users.php"
    }
  },
  messages: {
    username: {
      required: "Enter your username",
      minLength: "At least 2 characters are necessary",
      remote: String.format("The name {0} is already in use")
    }
  }
});

Custom Validation Rule

And you can add custom code to test without using rules. Use the Validator AddMessage method. For example, you can validate a user name that would include all characters.

    <script type="text/javascript">
        $(document).ready(function () {

            $.validator.addMethod("username", function (value, element) {
                return this.optional(element) || /^[a-z0-9\_]+$/i.test(value);
            }, "Username must contain only letters, numbers, or underscore.");

            $("form").validate({
                rules: {
                    username_input: {
                        username: true,
                        required: true,
                        minLength: 2
                    }
                }
            });

        });

    </script>

For this HTML:

<label for="username_input">User Name</label>
<input id="username_input" name="username_input" size="25" minlength="2" />

Will display this:

image

There are lots of custom validators at jquery.validate.additional.js on Koders.com

H5Validate

h5Validate plugin provides the best support for the HTML5 validation attributes. Use this plugin support for both the required and pattern attributes.

You load h5Validate and then name CSS styles in your Javascript to define what the error looks like.

$("#customerForm").h5Validate({
    errorClass: "validationError",
    validClass: "validationValid"
});

Where validationError and validationValid are styles:

<style type="text/css">
        .validationError
        {
            border: solid 2px red;
        }

        .validationValid
        {
            border: solid 2px green;
        }
</style>

You can use a div whose style is set to no display to trigger the title attribute as error text. For example:

<label for="FirstName">Your Name:*</label>
<input id="FirstName" type="text" data-h5-errorid="invalid-FirstName" title="Required: Please provide your first name." required />
<div id="invalid-FirstName" class="ui-state-error message" style="display:none;">Not used. Error message will show the title.</div>

You can put your patterns into a library. Use $.h5Validate.addPatterns() to add your pattern.

You can also catch events for each element that is validated by the framework and after the form has been validated.

See h5Validate - HTML5 Form Validation for jQuery for details.

For more information

See:

 Top 10 tips for JavaScript Form Validation

HTML5 Form Validation from Stephen Walther’s blog ASP.NET, Metro, and HTML5

For more information about jQuery Validation, see About client-side form validation and frameworks


Next Up

Getting your data onto the client using jQuery to pass JSON.

Bruce D. Kyle
ISV Developer Evangelist | Microsoft Corporation

image