簡體   English   中英

jQuery 自定義驗證方法永遠不會被調用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM