Wednesday, September 3, 2008

Starting With jQuery - Validation Plug-in

This series of posts on using jQuery with no prior knowledge comes to its third iteration.  Today's post focuses on an introduction to the Validation Plug-in.  This plug-in extends jQuery by adding simple client-side validation to a given HTML form.  In future entries we'll examine some of the challenges this plug-in has with traditional ASP.Net web form applications; however, for this post, we'll focus on just the basics.

If you would like to review the previous posts in this series, please feel free to review the links below:

In order to use the Validation plug-in, you'll need to add a few things to your web page:

The jQuery Validation Plug-in that I'm using in this example was written by Jörn Zaefferer.  His web site houses all of the documentation I used to learn how to use the plug-in.  If, after reading this post, you want to explore more, I highly encourage anyone to go to his site.  It's a great resource.

The jQuery Validation Plug-in works by examining the DOM of an HTML form and then assigning rules to the various field elements.  Optional, custom messages can be assigned to these validation rules as well to enhance the user experience.

Before we dive into the plumbing of the Validation Plug-in, let's first draw up a simple HTML form.

  1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2: <html xmlns="http://www.w3.org/1999/xhtml">
  3:  
  4: <head>
  5:     <meta http-equiv="Content-Language" content="en-us" />
  6:     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7:     
  8:     <title>jQuery Example 3</title>
  9:         
 10:     <script type="text/javascript" language="javascript" src="Scripts/jquery-1.2.6.js"></script>
 11:     <script type="text/javascript" language="javascript" src="Scripts/jquery.validate.js"></script>
 12:     <script type="text/javascript" language="javascript">
 13:         //Our validation script will go here.
 14:     </script>
 15:         
 16:     <style type="text/css">
 17:     #container {
 18:         width: 350px;
 19:         height: 8em;
 20:         border: 1px #009933 solid;
 21:         background-color:#66FF66;
 22:         display:block;
 23:     }
 24:     
 25:     label, input{
 26:         margin:2px 0px 1px 4px;
 27:     }
 28:     
 29:     label {
 30:         margin-top:3px;
 31:         font-family:"Times New Roman", Times, serif;
 32:         font-size:1.1em;
 33:         font-weight:bold;
 34:     }
 35:     </style>
 36: </head>
 37:  
 38: <body>
 39: <div id="container">
 40:     <form id="TestForm">
 41:         <label for="txtFirstName">First Name: </label><br />
 42:         <input name="txtFirstName" type="text" id="txtFirstName" title="Please Enter a First Name" /><br />
 43:         <label for="txtLastName">Last Name:</label><br />
 44:         <input name="txtLastName" type="text" id="txtLastName" title="Pleaes Enter a Last Name"/><br />
 45:         <input type="submit" value="Submit" id="btnSubmit"  />    
 46:     </form>
 47: </div>
 48: </body>
 49: </html>

Copying the HTML above to a file and viewing it in a browser should present you with a form similar to the following image:

TestForm

Our HTML form, TestForm, is very simple.  It contains simply 2 set of labels and text boxes for the user to input a user's First and Last Name.  The text boxes have their Title attribute set for accessibility reasons and to be used by our validations.

There are two ways we can add validation to the form.  We can add it by predefining the rules per form field, or add the rules in programmatically.  For today's topic, we'll look at predefining the rules in the form's jQuery representation.

Like previous posts that focused around rounded corners and center alignment, we'll need to setup the validation rules when the document element is ready.

  1: $(document).ready(function(){
  2:     //validation implementation will go here.
  3: })

Inside the function to be called when the document element is ready, we're going to need to select our TestForm through jQuery and call the validate() function.  The validate() function allows us to set the rules (and messages later on) for each of our form fields.  Let's look at the code for our form.

  1: $("#TestForm").validate({
  2:     rules: {
  3:         txtFirstName: {
  4:             required: true
  5:         },
  6:         txtLastName: {
  7:             required: true,
  8:             minlength: 2
  9:         }
 10:     }
 11: });

The validate() function takes an array of objects for an input parameter.  In the above snippet of code, we are passing in a rules object.  This rules object has an entry for each of our text box fields of our form.  For our example, we are requiring that both fields are required and the Last Name field requires 2 or more characters.

That's it.  We have successfully wired up simple validation to our form.

Putting the JavaScript together we have the following code:

  1: ...
  2: <script type="text/javascript" language="javascript">
  3: //Our validation script will go here.
  4: $(document).ready(function(){
  5:     //validation implementation will go here.
  6:     $("#TestForm").validate({
  7:         rules: {
  8:             txtFirstName: {
  9:                 required: true
 10:             },
 11:             txtLastName: {
 12:                 required: true,
 13:                 minlength: 2
 14:             }
 15:         }
 16:     });
 17: })
 18: </script>
 19: ...

After we add our script to our HTML and refresh our browser, we can submit the form to find that our fields now show off our required field validations. 

RequiredFields

Filling in the First Name and only a single character for the Last Name we also see our minimum length validation in action as well.

Length

Something that you may notice is the error text is the same for each of the rules.  In addition, the error text is the same as the text box Title attribute values.  In order to change this error text, we can add another object to the validate() method of our script.  Let's append the object array parameter by adding a messages object as shown below.

  1: $("#TestForm").validate({
  2:     rules: {
  3:         txtFirstName: {
  4:             required: true
  5:         },
  6:         txtLastName: {
  7:             required: true,
  8:             minlength: 2
  9:         }
 10:     },
 11:     messages: {
 12:         txtFirstName: {
 13:             required: "* Required"
 14:         },
 15:         txtLastName: {
 16:             required: "* Required",
 17:             minlength: "* 2 Characters Required."
 18:         }
 19:     }
 20: });

Just like the rules object from before, the messages object contains elements of the same name as our form fields.  These elements contain a mapping between the rules and the message to display once validated.  If a rule is presented without a message, the Title attribute will be used still.

Making these updates and saving our HTML file, we can refresh our browser window to view the changes.

Required and Length

In the even that the Title attribute is not present, canned messages relative to the rules will be displayed in a similar fashion as the messages object that we just added.

Below is the full HTML code:

  1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2: <html xmlns="http://www.w3.org/1999/xhtml">
  3:  
  4: <head>
  5:     <meta http-equiv="Content-Language" content="en-us" />
  6:     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7:     
  8:     <title>jQuery Example 3</title>
  9:         
 10:     <script type="text/javascript" language="javascript" src="Scripts/jquery-1.2.6.js"></script>
 11:     <script type="text/javascript" language="javascript" src="Scripts/jquery.validate.js"></script>
 12:     <script type="text/javascript" language="javascript">
 13:         //Our validation script will go here.
 14:         $(document).ready(function(){
 15:             //validation implementation will go here.
 16:             $("#TestForm").validate({
 17:                 rules: {
 18:                     txtFirstName: {
 19:                         required: true
 20:                     },
 21:                     txtLastName: {
 22:                         required: true,
 23:                         minlength: 2
 24:                     }
 25:                 },
 26:                 messages: {
 27:                     txtFirstName: {
 28:                         required: "* Required"
 29:                     },
 30:                     txtLastName: {
 31:                         required: "* Required",
 32:                         minlength: "* 2 Characters Required."
 33:                     }
 34:                 }
 35:             
 36:             });
 37:         })
 38:     </script>
 39:         
 40:     <style type="text/css">
 41:     #container {
 42:         width: 350px;
 43:         height: 8em;
 44:         border: 1px #009933 solid;
 45:         background-color:#66FF66;
 46:         display:block;
 47:     }
 48:     
 49:     label, input{
 50:         margin:2px 0px 1px 4px;
 51:     }
 52:     
 53:     label {
 54:         margin-top:3px;
 55:         font-family:"Times New Roman", Times, serif;
 56:         font-size:1.1em;
 57:     }
 58:     </style>
 59: </head>
 60:  
 61: <body>
 62: <div id="container">
 63:     <form id="TestForm">
 64:         <label for="txtFirstName">First Name: </label><br />
 65:         <input name="txtFirstName" type="text" id="txtFirstName" title="Please Enter a First Name" /><br />
 66:         <label for="txtLastName">Last Name:</label><br />
 67:         <input name="txtLastName" type="text" id="txtLastName" title="Pleaes Enter a Last Name"/><br />
 68:         <input type="submit" value="Submit" id="btnSubmit"  />    
 69:     </form>
 70: </div>
 71: </body>
 72: </html>

That's it for this post.  Next week, I'll be back in my routine and will be exploring how to programmatically add and remove rules as well as to examine some of the other rules that are available out of the box.  Later, we'll dive into creating custom rules.

Download Code: Starting with jQuery - Validation Plug-In.zip

kick it on DotNetKicks.com

10 comments:

  1. Looking forward to your next post on dynamically adding rules. Been having trouble with it.

    ReplyDelete
  2. Hello Egger,
    Great post!
    Just one question
    Is it possible to refer the error messages not into labels but into "div" ?

    Thank you

    ReplyDelete
  3. hi, this is a nice tutorial to the basics as the docs are a bit scant on that. I like your use of the alternative (to providing class = "required" and so on in the inputs!) addressing of the inputs.

    You maybe should point out that txtFirstName in your example refers to the form elements 'name' as opposed to its 'id'.

    thanks for the bit on custom callbacks too!

    ReplyDelete
  4. Nice one mate. I have also added the link to your post in my Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance. Have a check below:

    http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/

    ReplyDelete
  5. Nice tutorial. Has helped and will help me a long way

    ReplyDelete
  6. very helpful beginners....thank youuu

    ReplyDelete
  7. This helped me out a bunch after much Googling :) Thanks!

    ReplyDelete
  8. Thank you so much for this post. Helped a jQuery beginner a great deal.

    ReplyDelete
  9. Really helpful post, many thanks!

    ReplyDelete