27 Sep

Playing with JQuery Validation library

Category:UncategorizedTag: , , :

New job (2 weeks in), new responsibilities, new tools to play with.  Amazingly (for me), one of the new tools is the JQuery Validation Library.  My diving into this also coincides with ScottGu’s announcement that Microsoft is creating their own CDN for JQuery and JQuery Validation

Bad news is that this means I’m behind.  That sucks.  I was using JQuery MONTHS before Microsoft officially started supporting it (at least 6 months – but I’m too lazy to look it up).  Anyway, now you can use Microsoft’s bandwidth to get JQuery to your customer’s browser with this line:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>

And you can add the JQuery Validation library like this:

<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js" type=”text/javascript”></script>

Note: see those end tags, great annoyance of my life, but you have to have them, you can’t do <script src=”http://…” />.  That sucks, but I’m learning to live with it.

Anyway, back to validation.

The more I play with this library, the more I like it.  It is very configurable, easily style-able, the documentation isn’t half bad, and the code is readable.

Getting Started with JQuery Validation:

The JavaScript Way:  OK, assuming you have JQuery and the JQuery Validation library included, lets start with a simple customer form:

   1: <form id="CustomerForm">

   2: <p>

   3: <label for="firstNameEdit">First Name:</label>

   4: <input id="firstNameEdit" type="text" />

   5: </p>

   6: <p>

   7: <label for="LastNameEdit">Last Name:</label>

   8: <input id="LastNameEdit" type="text" />

   9: </p>

  10: <p>

  11: <label for="EmailEdit">Email:</label>

  12: <input id="EmailEdit" type="text" />

  13: </p>

  14: <p>

  15: <button type="submit">Submit</button>

  16: </p>

  17: </form>

Nothing special there.  Just a bunch of inputs and labels.  If you hit the submit button, a postback is fired and the data is sent back to the server.

But, business requirements dictate that all fields are required.  Simple enough, using JQuery the hookup looks like this:

   1: $("#CustomerForm").validate({

   2:     rules: {

   3:       FirstNameEdit: { required: true },

   4:       LastNameEdit: { required: true },

   5:       EmailEdit: { required: true, email:true }

   6:     }

   7: });

OK, the first name, last name, and email will now be required.  I also threw a little extra in there: email validation.  If you submit the form like this will be added after any of the required fields:

   1: <label class="error" for="FirstName" generated="true">This field is required.</label>

Key part there is the ‘error’ css class which is great for styling the messages.  So you can use the ‘label.error’ in your css class.

Another way

You can also use css classes to setup which fields are required.  It is a nice and simple way to hook everything up, but it is not as easily configurable (as we will see in a moment):

   1: <form id="CustomerForm">

   2: <p>

   3: <label for="FirstNameEdit">First Name:</label>

   4: <input id="FirstNameEdit" type="text" class=”required”/>

   5: </p>

   6: <p>

   7: <label for="LastNameEdit">Last Name:</label>

   8: <input id="LastNameEdit" type="text" class=”required” />

   9: </p>

  10: <p>

  11: <label for="EmailEdit">Email:</label>

  12: <input id="EmailEdit" type="text" class=”required email”/>

  13: </p>

  14: <p>

  15: <button type="submit">Submit</button>

  16: </p>

  17: </form>

The the Javascript is actually much simpler:

   1: $("CustomerForm").validate();

And you will get the same results.  But, the rest of the samples will use the prior code setup.  Also note: you can mix and match the css style with the JavaScript style.

Moving the message

Next problem you might encounter is you want to move the messages to another part of the screen.  Remember, default behavior is the messages go next to the control.

To solve this we will add a div to the page:

   1: <div id="RegisterErrors" style="display:none">

I can setup the Validation library to use this by going back to the validate method and adding errorLabelContainer directive.

   1: $(“#CustomerForm”).validate({

   2: errorLabelContainer: $("#RegisterErrors"),

   3: rules: {

   4:         FirstNameEdit: { required: true },

   5:         LastNameEdit: { required: true },

   6:         EmailEdit: { required: true, email: true }

   7:     }

   8: });

Now this is great, but there is still a problem.  Each of the messages will be “This field is required”.  That doesn’t say which field is the problem.  Lets add custom messages for each field.


   2:     $("#CustomerForm").validate({

   3:     errorLabelContainer: $("#RegisterErrors"),

   4:     rules: {

   5:             FirstNameEdit: { required: true },

   6:             LastNameEdit: { required: true },

   7:             EmailEdit: { required: true, email: true }

   8:         },

   9:         messages: {

  10:             FirstNameEdit: "First name is required",

  11:             LastNameEdit: "Last name is required",

  12:             EmailEdit: "Valid email address is required"

  13:         }

  14:     });

Which then gives better messages.

For next time

Ok, this is not all the JQuery Validation library can do, there is a lot more, but this is enough for now.  Next post will show how to validate fields using web service results, and various callbacks that can be used to customize the library.

32 thoughts on “Playing with JQuery Validation library

  1. Pingback: Servefault.com
  2. how come for the label id’s you have EmailEdit, LastNameEdit..etc, But in the javascript they are called threw Email, and LastName (missing the Edit at the end)??

  3. Hey guys, you are absolutely correct, I had some errors in my samples.

    Note to self: don’t reformat the code post from your sample code…you miss stuff.

    Anyway, the code should be much closer. Sorry about that everyone, I’m usually better about that sort of thing.

    @Anthony: the ‘Edit’ has to be there.
    @SeanJA: what you saw in an artifact for code for my next post.

  4. @ianh: We use a custom validation library that one of our guys wrote.

    But you could also look at the NHibernate Validation library or Microsoft’s Validation Block (PnP).

  5. I tried using this library and found it to be great provided your not using asp.net.

    You can forget using it with the asp.net controls because the names are dynamically generated. You’d need to place the javascript in the same file as the aspx/ascx file and use Control.ClientID, which i find to be a problem as I like to have my javascript in one file so it can be cached by the browser.

  6. @Vince, first off, you are referring to Asp.Net WebForm, that statement is not valid with Asp.Net MVC. Also, with WebForm 4.0 (coming with VS 2010) one of the new features is settable ClientID.

    Anyway, for Webforms, here is a work-around that I use:

    Create a PageControls object.
    So the one piece of javascript on my page does this:
    var PageControls = {
    FirstNameID: “”,
    LastNameID: “”

    Then I can access the PageControls variable from anywhere.

    That works well for Pages (aspx) files, but there is more work for controls (ascx), but the general idea is still valid.

  7. Hello,

    I was just wondering if there is a way to move/style the “success” message also. would it be something like

    successLabelContainer: $(“#RegisterSuccess”), ???

  8. Chris,

    Great post. So when the user submits the postback begins. If the form does not pass the client-side validation rules (specified above) does this library intercept the HTTP request? I’m assuming it does.


  9. Nice post. I’ve been using jQuery Validation on a project for a while, and one thing that I’ve discovered is that since you need to apply a css class to the tags you now have great flexibility. In particular you can enable and disable required fields client-side on-the-fly.

    Consider a wizard where each subsequent section is driven by previous answers. With a little jQuery you can assign or un-assign the “required” class as needed.

    For those who have had trouble with ASP.Net web forms, you can avoid the awful mangled id issues with the use of the ClientId property, or in some cases just use the CssClass property to assign valid id’s to a form control.

  10. can not get jquery to validate based on id’s. So far it only works on form names. Your example show that it will validate based on id.

  11. That is something I discovered a week or two ago as well. If your controls have ID’s and Names, the Names are used instead of the IDs.

    If you want to base things off of ID values, you have to remove the name values.

  12. I am such a noob at Jquery Validation it is not even remotely funny (unless you consider being fired from your job for being an idiot funny)…  That being said, I am wondering if there isn’t a way I can place form validation stuff inside each form element, and then somehow loop through each form element using JavaScript, and validate from there?  Do I sound crazy or can that be done?

Comments are closed.