开发者

jQuery validation - limit input to 3 specific lengths

开发者 https://www.devze.com 2023-01-21 00:20 出处:网络
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, a

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 maxleng开发者_如何学运维th: 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.


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]
             },
  ...
0

精彩评论

暂无评论...
验证码 换一张
取 消