Filed under: Web | Tags: addmethod, age, agerange, javascript, jquery, plugin, validation
I’m a huge fan of the jQuery Validation plugin, it’s a powerful means of form validation that saves me umpteen hours of coding it myself. A project I’ve been working on (inherited recently, actually) requires people to enter the year in which they were born, and then on another page (oh yay!) the survey wants to know their current age. In order to do this I needed to add a few hidden variables on the next page (minage, maxage) that take into account the fact that they may not yet have had their birthday (hence the range) when filling in the survey. That was the easy part! Next came getting the Validation plugin to use these values with its built-in range rule, or using the min: and max: rule types. The problem I had was that neither of these allows me to specify variables, and attempts to use PHP to write them weren’t working either.
Thankfully Validation is extensible via the addMethod plugin, and despite lack of solid documentation for this method I managed to get things going this afternoon:
$.validator.addMethod(“ageRange”, function(value,element, params)
{
var vmin = $(params[0]).val();
var vmax = $(params[1]).val();
return ((value >= vmin) && (value <= vmax));
});
You instantiate this using the following code:
$(“#myform”).validate(
{
//validation rules
rules: {
age: { required: true, ageRange: ["#minage","#maxage"] }
}
});
#minage and #maxage of course being the ID’s for the hidden form variables. The code could of course be enhanced so that min and max could be either way around, but heck I can’t be bothered. Hope that’s of use to someone.
No Comments Yet so far
Leave a comment
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>




