Monday, March 24, 2008

jQuery Validation Plugin

We start to see several plugins in the web based on the jQuery library. I have the chance today to work a bit with a plugin called: jQuery Validation Plugin by Jörn Zaefferer - which enable you to apply client validation to your web forms using jQuery.

To get started, you have to download the plugin files from this link. And sure the jQuery library as well: jQuery 1.2.2. Then, you should have: jquery.validate.js and jquery.js files reside on your project somewhere and linked in your markup.

IMPORTANT NOTE: I had a problem when using jquery.validate with the new vesrions - higher than 1.2.2 - of jQuery library. jquery.validate uses functions in jQuery library which no longer exist.

The following sample is the simplest one. You use the selector to get the form element. Then, you call the validate function.

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


In this case, you will have to set some predefined metadata in the class attribute of the elements telling the library the required rules to apply for the form inputs.
<form id="simpleSignUpForm" action="" method="get">
        <input type="text" id="firstname" class="required" minlength="2"/>
        <input type="text" id="lastname" class="required" minlength="2"/>
        <input type="text" id="username" class="required" minlength="2"/>
        <input type="text" id="email" class="required email" minlength="2"/>
        <input type="text" id="password" class="required" minlength="8" />
        <input type="text" id="website" class="url" />
        <input type="submit" value="Submit" />
</form>


In this case, the plugin will use some defaults error messages for validating the inputs. However, you can have more controls on the errors and rules. The following sample show in details how you can validate a full sign up form elements by specifying the rules with the associated error messages. In this sample, you won't have to apply any CSS styles as you already defines explicitly your rules.
<script type="text/javascript">
        $(document).ready( function() {
               $("#signupForm").validate({
                           rules:{
                                           username:{
                                                               required:true,
                                                               minlength:2
                                           },
                                           password:{
                                                               required:true,
                                                               minLength:5
                                           },
                                           confirm_password:{
                                                               required:true,
                                                               minlength:5,
                                                               equalTo:"#password"
                                           },
                                           email:{
                                                               required:true,
                                                               email:true
                                           },
                                           topic:{
                                                               required:"#newsletter:checked",
                                                               minLength:2
                                           },
                                           agree:"required"
                            },
                            messages:{
                                           username:{
                                                               required:"Please enter a username",
                                                               minLength:"Your username must consist of at least 2 characters"
                                           },
                                           password:{
                                                               required:"Please provide a password"                                                                minLength:"Your password must be at least 5 characters long"
                                           },
                                           confirm_password:{
                                                               required:"Please provide a password",
                                                               minLength:"Your password must be at least 5 characters long",
                                                               equalTo: "Please enter the same password as above"
                                           },
                                           email: "Please enter a valid email address",
                                           agree: "Please accept our policy"
                            }
               });
        }
</script>






For more information about the methods you can use for the validation, check it here.

The way you define your rules and messages are unified and configurable. You define a message per rule which is extremely a need in any web project. It's common to have several validation rules with different error messages in the same web form. When I see this style, I just remember the Design by Contract style in which your requirements (contract) are easily mapped to rules (benefits and obligations). It's similar as you put all your quality matrix in one place. Besides, it's easy to modify as like as you set some configurations to your web form!

Another point to mention is the different scenarios you can have and how this library fit it. In the last sample, you can see how you check for password confirmation, input formats (emails, URLs ... etc.) and user selections.

You can modify the CSS style of your validation errors - i.e how the input controls will look like in case of a validation error occurred. You simply modify the following snippet to have different look for the validated inputs.

div.error { display: none; }
input { border: 1px solid black; }
input:focus { border: 1px dotted black; }
input.error { border: 1px dotted red; }




This plugin is perfect for ASP.NET MVC. Actually, there is already some tries like Validator Toolkit for ASP.NET MVC which enable client and server side validation for MVC. It uses jQuery as well for the client validation. I don't think jQuery Validation is easy to be used in ASP.NET web forms as the page structure actually differs. However, we may find some other versions suitable for ASP.NET Web Forms in the future.

Unlike the ASP.NET validation controls which you need to inject inside your markup, jQuery Validation Plugin puts all the validation rules in one place. I think this really a benefit. In fact, this is one of the benefits of using jQuery itself - thanks for the nice selectors. This style definitely enhance your code readability by separating the validation stuff away from the markup giving the designers - and even the devs - more clean markup to work in.

4 comments:

Leftend said...

Thanks for the tip. One question, how do you get the rules to work with the auto-generated ID's that ASP.NET outputs on it server controls?

For example, I named one of my textboxes: "txtTitle" - but when it's output on the page, it becomes: "ctl00_MainColumn_txtTitle"

Thanks.

Mohammed Nour said...

For the first style of the validation in the post, you can get the client ID of the form in the javascript code like the following:

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

And your markup will be like:

<form id="form1" runat="server">
        <asp:TextBox ID="firstname"
CssClass="required" runat="server"></asp:TextBox>
        <asp:Button ID="btnSubmit" runat="server" />
</form>

You can use the same way for the other style of validation but you will need to use this client id thing for all the controls you validate.

Anonymous said...

Greetings Mohammed!

I'm still in the process of learning Javascript and JQuery and found this to be the most easiest walk through on how to get the best desired results for JQuery validating that I have found. You have helped me immensely in finalising my assignment so thank you very much! :)

Ashish Kumar said...

How to use this with master and content pages i want to validate few fields in my content page.
After using this my form is not posting back how to again enable my asp.net button to do postback after all validations have been checked