这是我一直在开发的页面的简化版本;我进行了一些基本验证工作 here但我想与 jQuery 验证器集成以获取内联错误消息而不仅仅是警报框。
<html>
<head>
<title>pick a box, its contents will help you on your way!</title>
<script src="jQuery-1.4.4-min.js"></script>
<script src="jQuery-validate.js"></script>
</head>
<body>
<form id="fred">
<input class="Notes8" name="Notes8~1" id="Notes8~1" type="checkbox" value="Yes"> Option 1<br>
<input class="Notes8" name="Notes8~2" id="Notes8~2" type="checkbox" value="Yes"> Option 2<br>
<input class="Notes8" name="Notes8~3" id="Notes8~3" type="checkbox" value="Yes"> Option 3<br>
<script type='text/javascript'>
jQuery(function($) {
function validateMultiple (selector, n, isExactlyN) {
const totChecked = $(selector).filter(':checked').length;
return !(isExactlyN ? totChecked == n : totChecked >= n);
}
jQuery.validator.addMethod('.Notes8',
function(value, element) {
return validateMultiple('.Notes8', 1);
},
'Please check at least one check box.');
});
</script>
<button type="submit">SUBMIT!</button>
</form>
</body>
</html>
问题是,jQuery.validator.addMethod
调用似乎不起作用;不进行验证,如果我将 alert("FRED");
放入 function(value, element)
中,则不会显示任何内容,表明验证器方法从未连接正确地起来。为什么是这样?如何在提交表单时执行验证功能?我在浏览器控制台中没有看到 JavaScript 错误。
最佳答案
您忘记调用validate
方法:$("#fred").validate();
。您的验证代码也存在问题 - 我删除了不必要的否定。另外,您不需要 addMethod
中的 name
参数中的点。 .
<html>
<head>
<title>pick a box, its contents will help you on your way!</title>
<script src="jQuery-1.4.4-min.js"></script>
<script src="jQuery-validate.js"></script>
</head>
<body>
<form id="fred">
<input class="Notes8" name="Notes8~1" id="Notes8~1" type="checkbox" value="Yes"> Option 1<br>
<input class="Notes8" name="Notes8~2" id="Notes8~2" type="checkbox" value="Yes"> Option 2<br>
<input class="Notes8" name="Notes8~3" id="Notes8~3" type="checkbox" value="Yes"> Option 3<br>
<script type='text/javascript'>
jQuery(function ($) {
function validateMultiple(selector, n, isExactlyN) {
var totChecked = $(selector).filter(':checked').length;
return (isExactlyN ? totChecked == n : totChecked >= n);
}
jQuery.validator.addMethod('Notes8',
function (value, element) {
return validateMultiple('.Notes8', 1);
},
'Please check at least one check box.');
});
$("#fred").validate();
</script>
<button type="submit">SUBMIT!</button>
</form>
</body>
</html>
关于javascript - jQuery.validator.addMethod 没有被执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59956561/