Hi, I'm using jQuery as the validation tool for all of my forms and I have a request to limit the length of the inputs on one field to 8, 12, or 13 characters only. Now, I'm already doing minlength: 8, and maxlength: 13 to take care of the upper and lower limits but haven't figured out how to limit the entry to exactly one of the three lengths.
+1
A:
You could add a custom validation method. Here is some rough code to get you started:
jQuery.validator.addMethod("specific_lengths", function(value, element, param) {
if (this.optional(element)) return;
for (var i = 0; i < param.length; i++){
if (this.getLength($.trim(value), element) == param[i])
return true;
}
return false;
});
You could then hook up the validation like this:
jQuery("#myform").validate({
rules: {
myField: {required: true,
specific_lengths: [8, 12, 13]
},
...
Justin Ethier
2010-10-21 15:36:50
Thanks, that worked perfectly! (although I changed the last line of the custom validation to "});")
WannabeVagabond
2010-10-21 15:52:32
You're welcome! I just updated the answer with your correction - the code was written off-the-cuff so it was a bit raw :)
Justin Ethier
2010-10-21 16:09:17