我正在使用 jQuery 验证来验证表单,我想做的是这样...我希望将其设置为,例如,如果选中复选框,则验证编辑框的方式会有所不同。
如果未选中该复选框,这就是验证的方式:
weight: { required: true, max: 50 }
如果检查的话,这就是验证它的方式。
weight: { required: true, max: 100 }
有什么想法吗?
最佳答案
您可以使用Validate plugin's built-in rules('add')
method每当单击复选框时动态更改规则。
jQuery:
$(document).ready(function () {
// initialize the plugin
$('#myform').validate({
// other options,
rules: {
// other rules,
weight: {
required: true,
max: 50 // initial value on load
}
}
});
// change the rule on checkbox and update displayed message dynamically
$('#check').on('change', function () {
if ($(this).is(':checked')) {
$('#weight').rules('add', {
max: 100
});
} else {
$('#weight').rules('add', {
max: 50
});
};
$('#weight.error').each(function () {
$(this).valid();
});
});
});
HTML:
<form id="myform">
<input type="checkbox" id="check" />
<input type="text" id="weight" name="weight" />
<input type="submit" />
</form>
关于jquery - 选中复选框时动态更改 jQuery 验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784705/