Saturday, June 4, 2011

Client-side validation with jQuery validation plugin. Basic concepts.

jQuery validation plugin is my favorite framework for client-side validation. I'm surprised more and more about its power and flexibility. Before I start to describe my recently task for client-side validation I would like to say few words how this plugin works at all. jQuery validation plugin has a predefined set of validation methods for required fields, emails, URLs, credit card, numbers, dates, etc. All bundled methods come with default error messages in english and translations into 32+ languages. By default, error messages are displayed after the invalid element, but this is also customizable. It is also possible to put them into an error container at some other places and show them bundled all together. Desired validation methods can be specified in two ways:

1) By HTML "class" attribute.
2) By rules in JavaScript.

The first way is simple. Assume, you have a form with Id "registerForm" containing fields "Name" and "E-mail". Both fields should be required. In additional, the field "Name" requires minimum 3 letters and the field "E-mail" accepts only valid e-mail inputs.
<form id="registerForm" method="get" action="...">
    <label for="name">Name</label>
    <input id="name" name="name" size="25" class="required" minlength="3" />
    <label for="email">E-Mail</label>
    <input id="email" name="email" size="25" class="required email" />
</form>
Validation methods are specified here by "class" attributes. The form can be validated now by the call
 
jQuery("#registerForm").validate();
 
How does this plugin behave? By default, forms are validated on submit, triggered by the user clicking the submit button or pressing enter when a form input is focused. There is also validation on single elements on demand.
var validator;

jQuery(document).ready(function(){
     validator = jQuery("#registerForm").validate();
     ...
     doSomething();
});

function doSomething() {
    var isNameValid = validator.element("#name");
    if (isNameValid) {
        // do something
        ...
    }
}
The call validator.element("#name") above validates a single field "Name" and returns true if it is valid, false otherwise.

Before submitting the form for the first time the validation is lazy. The user can tab through fields without getting annoying messages. He has a chance to correct input values. Once a field was marked invalid, it is eagerly validated. The plugin validates on keyup if the user types something. When the user enters something invalid into a valid field, it is also validated when the field loses focus (onblur). In addition, a field can be highlighted as invalid. As soon as the user entered the necessary value, the error message is removed.

I prefer the second way - validation by rules definitions via JavaScript. This is more flexible and leaves nothing to be desired - there are many configuration parameters. Rules and messages can be configured in the validate(...) method. Each rule specifies Id of the field to be validated and desired validation methods for this field.
jQuery("#registerForm").validate({
    rules: {
        name: {
            required: true,
            minlength: 3
        },
        email: {
            required: true,
            email: true
        }
    },
    messages: {
        name: "Please enter a valid name.",
        email: "Please enter a valid e-mail."
    }
});
Rules can be added dynamically too after validate() was called. Like this one for the field with Id "name" above.
 
jQuery("#name").rules("add", {minlength: 3});
 
Validation methods can be grouped as one. For example if you want to group all three built-in validation methods "required", "date" and "dateRange", you can write
jQuery.validator.addClassRules({
    requiredDateRange: {required:true, date:true, dateRange:true}
});
The new validation method is called now "requiredDateRange". Another nice feature - overwriting of default messages. Example for "required" and "date" validations:
jQuery.extend(jQuery.validator.messages, {
    required: "These fields are required",
    date: "Please specify valid dates"
});
Last but not least - adding of new validation methods by
 
jQuery.validator.addMethod(name, method, [message]);
 
In the next post I will show an example for jQuery.validator.addMethod and more other advanced tricks. Stay tuned.

1 comment:


  1. In software project management, software testing, and software engineering,
    verification and validation (V&V) is the process of checking that a software system meets specifications and that it fulfills its intended purpose.
    It may also be referred to as software quality control.

    software validation

    ReplyDelete

Note: Only a member of this blog may post a comment.