简体   繁体   English

jQuery 自定义验证方法永远不会被调用

[英]jQuery custom validation method never gets called

I have some HTML and JavaScript similar to this:我有一些与此类似的 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>

Now for some reason when I go to validate the form, the custom validation method never gets called, even though I think I set it up properly.现在出于某种原因,当我去验证表单时,自定义验证方法永远不会被调用,即使我认为我正确设置了它。 Thus "ok" is always displayed;因此总是显示“ok”; the validation never fails because the method which does the validation is not called.验证永远不会失败,因为没有调用进行验证的方法。 Why is this?为什么是这样? What am I missing here to hook up the validation?我在这里缺少什么来连接验证?

I figured it out: I needed to set a name="TotalHours" on the first input field;我想通了:我需要在第一个输入字段上设置一个name="TotalHours" the id is not sufficient. id是不够的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM