jQuery Validation maxlength parameter based on conditional

依然范特西╮ 提交于 2021-01-29 04:55:17

问题


How to change the maxlength of a textbox using jQuery Validation based on a condition.

Code

 SSN: { required: true, minlength: 9, maxlength: 9 }

How do I change the maxlength based on an if-else condition?


回答1:


Would a ternary expression be what you want ?

SSN: { required: true, minlength: 9, maxlength: ((condition)?true:false) }

Exemple :

SSN: { required: true, minlength: 9, maxlength: ((my_var=="short")?13:17) }

Would print 13 if the condition is met, otherwise 17

Edit: Correcting the max lenght so it is bigger than the min lenght.




回答2:


You can use a function within the rules option to return the desired parameter based on a certain dynamic condition.

In the demo below, clicking a checkbox will set the maxlength to 12, otherwise it's 15.

$('#myform').validate({
    rules: {
        SSN: {
            required: true,
            minlength: 9,
            maxlength: function(element) {
                return $('#foo').is(':checked') ? [12] : [15];
            }
        }
    }
});

DEMO: http://jsfiddle.net/ny6ahnh0/




回答3:


As this doc shows, I think that you can change maxlength by the maxlength method :

$( "#yourTextBox" ).validate({
  rules: {
    field: {
      required: true,
      maxlength: function(){
        return condition ? valueIfTrue, valueIfFalse;
      }
    }
  }
});

EDIT : As @Sparky pointed out, the configuration cannot be reinitailized. So the maxlength should be changed by a callback function.



来源:https://stackoverflow.com/questions/28721427/jquery-validation-maxlength-parameter-based-on-conditional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!