问题
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