Playing with JQuery Validation library
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:
And you can add the JQuery Validation library like this:
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:
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:
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:
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.
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):
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:
I can setup the Validation library to use this by going back to the validate method and adding errorLabelContainer directive.
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.
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.