[英]jQuery custom validation method never gets called
我有一些与此类似的 HTML 和 JavaScript:
<html>
<head>
<title>Validation Test</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
</head>
<body>
<form id="myform">
<input id="TotalHours" type="text" value="24"/> is the total number of hours!
<input id="day" class="input" type="text"/> is the number of hours of daylight!
<input id="night" class="input" type="text"/> is the number of hours of darkness!
<script>
validationRules = {
TotalHours: {
TotalHoursMatch: true
}
};
$.validator.addMethod("TotalHoursMatch", function(value, element) {
// find total hours
var reportedTotalHours = parseFloat($("#TotalHours").text());
var totalHours = 0;
$('input.input').each(function(i, sel) {
var hours = $(sel).find(":selected").text();
var f = parseFloat(hours);
if (f != 0 && !Number.isNaN(f))
totalHours += f;
});
// validate that hours are within a quarter hour of each other
var difference = Math.abs(totalHours - reportedTotalHours);
return difference < 0.25;
}, "Total of hours for daylight and darkness must match total hours in a day.");
function doSubmit()
{
$('form').validate({rules: validationRules});
if (!$('form').valid())
alert('bad!');
else
alert('ok');
}
</script>
<button onclick="doSubmit();">submit</button>
</form>
</body>
</html>
现在出于某种原因,当我去验证表单时,自定义验证方法永远不会被调用,即使我认为我正确设置了它。 因此总是显示“ok”; 验证永远不会失败,因为没有调用进行验证的方法。 为什么是这样? 我在这里缺少什么来连接验证?
我想通了:我需要在第一个输入字段上设置一个name="TotalHours"
; id
是不够的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.