gpt4 book ai didi

jquery - 选中复选框时动态更改 jQuery 验证规则

转载 作者:行者123 更新时间:2023-12-03 22:58:46 25 4
gpt4 key购买 nike

我正在使用 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>

工作演示:http://jsfiddle.net/3hGxS/

关于jquery - 选中复选框时动态更改 jQuery 验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com