JQuery Form Validation Plugin

This weekend I sat down intent on finishing a portion of my media management application and testing different strategies regarding client side validation of data using the JQuery Validation Plugin (link).

My initial impressions of this plugin were, at first, not very positive, though a lot of this was the learning curve associated with grasping the rather fragmented documentation in certain areas.  Basically what I was looking for from a plugin was to easily be able to define standard validation requirements (required, minlength, equality, range) easily, as well as the flexibility to define my own( Asynchronous uniqueness check against a database ).

Below is some code from my application demonstrating the definitions of required and minlength rules:

$("form").validate({
     rules: {
          seriesName: {
               required: true,
               minlength: 2
          }
     },
     messages: {
          seriesName: {
               required: "Field is required",
               minlength: "Name must be at least 2 characters"
          }
     },
     errorElement: "div"
});

The idea here is that the parent key names (seriesName in this case) relate to the form elements themselves.  The documentation on what can be done is very skimpy, and takes a fair amount of deduction to figure out. If you look here you can get an idea of the types of validation rules that exist.  But, if your like me, you want to see this in code to see how its used, and for that there is a good example provided here, just do a view source to see the code.

Most of this will be focused with what rules you can define for various elements, the next step would be how do you communicate to the user what is wrong and what is the flexibility of what you can do.  Based on the provided examples, and my own experience, I was able to mutate the type of container the error messages were being displayed with, and the class, thus I could properly style and display them in any manner I desired.  There are a whole host of options for controlling this behavior, listed here.

In the example I provided above, I took most of the default and simply changed the element type to a

instead of label, which is the default element.

So at this point, we have a relatively simple call to a JavaScript method that allows us to use rule based validation setup without coding a lot of redundant JavaScript to perform the validation.  Validate will also internally check if the selected form is valid and suppress the submit if it is not valid.

The final component I was looking for was a way to implement custom validation and I was very impressed with how the Validation plugin handles this.  First some code:

$.validator.addMethod("IsUniqueName", function(value, element) {
     var id = Number($("#seriesId").val());
     var result = $.ajax({
          async: false,
          type: "GET",
          url: GetApplicationPath("#hidAppPath")
                    + "/Series/AjaxCheckSeriesName",
          data: { seriesName: value, seriesId: id },
          cache: false,
          dataType: "json"
     });
 
     if (result.responseText == "false")
          return false;
     else
          return true;
            
}, "Series name must be unique");

I found this to be very ingenious and admitting confusing the first time I read the documentation (though it was 4am and I had just finished Wave 50 Hardcore on Security in GoW2), but its actually rather simple.  If you notice above we have the key’s required and minlength, these are simply built in definitions, but using the addMethod we can add our own internal rules.

In the case above, I am creating a new rule called IsUniqueName and defining as its function check a routine to make a call to a routine to verify the provided name is unique.  The final parameter is the message to be displayed in the event the two values (expected and actual) do not match up.  To specify the expected, we modify our existing call to validate as such:
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

rules: {
     seriesName: {
          required: true,
          minlength: 2,
          IsUniqueName: true
     }
},

Notice the new addition here, we are saying that for the rule IsUniqueName we are expecting a value of true from the callback.  Notice that I am using a block Ajax call to determine this, mainly because a callback would not be able to directly return the handler.  This is a weakness of doing this kind of check inline, instead of having the user request it.

Overall, I found that working with this plugin to be a little bit confusing at first and the documentation seemed scattered.  However, the more I stayed with it the easier it became.  This plugin adequately offers the ability to easily do standard validation as well as custom validation with a minimal amount of custom code needed.  This is important as validation tends to have a lot of redundancy involved in performing it, so a tool such as this makes that process much less error prone.  I should point out that the total LOC was 39 lines for everything that I am doing.  The amount of time this will save in future projects is well worth learning this tool and finding out all it has to offer, and that is actually quite a bit.

Below are the links I referenced in this article:

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Advertisement

One thought on “JQuery Form Validation Plugin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s