表格不会验证

时间:2015-11-28 22:20:20

标签: jquery html forms

所以我试图让这个表格正常工作,它似乎根本不想做任何事情。表单的要点是创建一个带有错误类和值为" *"的span元素。如果表单是错误的,那还不是真的需要检查任何内容,所以我认为代码是正常的。但其余部分应该在允许提交之前验证所有输入都已填写,确保夜间输入为数字,然后检查电子邮件输入是否与emailPattern变量匹配。但它没有做任何事情。如果我进入" eeee"在Nights输入框中,它只是继续提交表单。我究竟做错了什么?注意:此JavaScript是唯一需要编辑的JavaScript。我知道HTML中包含了另外两个,但是唯一需要编辑的是这里的JavaScript部分,因为我需要编辑它。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Reservation request</title>
    <link rel="stylesheet" href="main.css">
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="jquery.validate.min.js"></script>
    <script src="additional-methods.min.js"></script>   
    <script src="reservation.js"></script>
</head>

<body>
    <h1>Reservation Request</h1>
    <form action="response.html" method="get"
        name="reservation_form" id="reservation_form">
        <fieldset>
            <legend>General Information</legend>
            <label for="arrival_date">Arrival date:</label>
            <input type="text" name="arrival_date" id="arrival_date" autofocus><br>
            <label for="nights">Nights:</label>
            <input type="text" name="nights" id="nights"><br>
            <label>Adults:</label>
            <select name="adults" id="adults">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>                                                
            </select><br>
            <label>Children:</label>
            <select name="children" id="children">
                <option value="0">0</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>                                                
            </select><br>           
        </fieldset>
        <fieldset>
            <legend>Preferences</legend>
            <label>Room type:</label>
            <input type="radio" name="room" id="standard" class="left" checked>Standard&nbsp;&nbsp;&nbsp;               
            <input type="radio" name="room" id="business" class="left">Business&nbsp;&nbsp;&nbsp;
            <input type="radio" name="room" id="suite" class="left last">Suite<br>
            <label>Bed type:</label>
            <input type="radio" name="bed" id="king" class="left" checked>King&nbsp;&nbsp;&nbsp;
            <input type="radio" name="bed" id="double" class="left last">Double Double<br>
            <input type="checkbox" name="smoking" id="smoking">Smoking<br>
        </fieldset>     
        <fieldset>
            <legend>Contact Information</legend>
            <label for="name">Name:</label>
            <input type="text" name="name" id="name"><br>
            <label for="email">Email:</label>
            <input type="text" name="email" id="email"><br>
            <label for="phone">Phone:</label>
            <input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
        </fieldset>

        <input type="submit" id="submit" value="Submit Request"><br>

    </form>
</body>
</html>

JavaScript&amp; JQuery的

新的仍然无法运作,但由于理查德

,因此组织得更好,准备更充分
$(document).ready(function() {
    var emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
    $("input").add("span").addClass("error").value("*"); // adding span with class of error and value of *
    $("#arrival_date").focus;

    $("#submit").click(function(e) { // variable to filter for empty inputs
        var empty = $(this).parent().find("input").filter(function() {
            return $(this).val() === "";
        });
        if (empty.length || 
            $.isNumeric($("#nights").val()) || 
            $("#email").value != emailPattern) {
                e.preventDefault();
            }

       function storeValues(form)  { //function to store cookie values from input boxes
            setCookie("arrival_date", form.arrival_date.value);
            setCookie("nights", form.nights.value);
            setCookie("name", form.name.value);
            setCookie("email", form.email.value);
            setCookie("phone", form.phone.value);
            return true;
        }
    }
}); // end ready

以前就是这个

$(document).ready(function() {
    var emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
    $("input").add("span").addClass("error").value("*"); // adding span with class of error and value of *
    $("#arrival_date").focus;

    $("#submit").click(function() { // variable to filter for empty inputs
    var empty = $(this).parent().find("input").filter(function() {
        return this.value === "";
    });
    if  ( ($("input").val()) == (empty)) {
        $("form").submit(function (e) { // function to stop submitting form if any values return empty
            e.preventDefault();
        });
    }
    if {
        $.isNumeric($("#nights").val())) { // function to check id nights for being numeric and stopping form if not
            $("form").submit(function (e) {
                e.preventDefault();

            }
        }
    }
    if $("#email").value != emailPattern { // function to stop form if id email does not match variable emailPattern
        $("form").submit(function (e) {
            e.preventDefault();
        }
    }
    $("#submit").click(function() {
        function storeValues(form)  { //function to store cookie values from input boxes
            setCookie("arrival_date", form.arrival_date.value);
            setCookie("nights", form.nights.value);
            setCookie("name", form.name.value);
            setCookie("email", form.email.value);
            setCookie("phone", form.phone.value);
            return true;
        }

    });
}); // end ready

2 个答案:

答案 0 :(得分:1)

问题在于这行代码

if ($("input").val()) == (empty)

$("input")返回输入元素的HTML集合,其中有很多。您必须选择$("input")[0]之类的索引或遍历整个集合。

您已经有一个变量用于查找空输入元素的数量。所以在这种情况下你只需要得到那个数字。

还有一种方法可以使这段代码更加干燥。您在三个不同的时间呼叫相同的click event handler。只需要一个电话。

您希望验证在三个条件下失败

  1. 有些字段尚未填写
  2. 输入数字
  3. 电子邮件有效
  4. 我们可以将它们合并为一个,而不是创建三个独立的条件。

    $(document).ready(function() {
        var emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
        $("input").add("span").addClass("error").value("*"); // adding span with class of error and value of *
        $("#arrival_date").focus;
    
        $("#submit").click(function(e) { // variable to filter for empty inputs
            var empty = $(this).parent().find("input").filter(function() {
                return $(this).val() === "";
            });
            if (empty.length || 
                $.isNumeric($("#nights").val()) || 
                $("#email").value != emailPattern) {
                    e.preventDefault();
                }
    
           function storeValues(form)  { //function to store cookie values from input boxes
                setCookie("arrival_date", form.arrival_date.value);
                setCookie("nights", form.nights.value);
                setCookie("name", form.name.value);
                setCookie("email", form.email.value);
                setCookie("phone", form.phone.value);
                return true;
            }
        }
    }); // end ready
    

答案 1 :(得分:1)

Working JSFiddle

您的行$("input").add("span").addClass("error").value("*");导致了TypeError,您的部分if语句未正确构建,并且您的电子邮件验证程序未接受某些电子邮件地址。

我使用this SO answer作为电子邮件功能:

function validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
}

要检查空输入,我使用this SO answer检查空格。

var $fields = $(".form :input");
var $emptyFields = $fields.filter(function() {
    // remove the $.trim if whitespace is counted as filled
    return $.trim(this.value) === "";
});

另外,我整合了您的验证逻辑。

新Javascript

$(document).ready(function () {
    $("#arrival_date").focus;
    var $fields = $("#reservation_form").find('input');
    $("#reservation_form").submit(function (e) {
        var $emptyFields = $fields.filter(function () {
            // remove the $.trim if whitespace is counted as filled
            return $.trim(this.value) === "";
        });
        if ($emptyFields.length || !$.isNumeric($("#nights").val()) || !validateEmail($("#email").val())) {
            e.preventDefault();
        }

        function storeValues(form) { //function to store cookie values from input boxes
            setCookie("arrival_date", form.arrival_date.value);
            setCookie("nights", form.nights.value);
            setCookie("name", form.name.value);
            setCookie("email", form.email.value);
            setCookie("phone", form.phone.value);
            return true;
        }
    });

    function validateEmail(email) {
        var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        return re.test(email);
    }
});