简单的表单验证不起作用

时间:2017-09-14 01:49:28

标签: javascript forms validation

尝试遍历所有字段,并将表单上方写的错误,自动对焦和背景颜色更改为红色...

表单不起作用。

为什么?

奖励积分:如果您能解释如何在errorMessages中单独命名字段,我们将非常感激...

代码:

<html>
    <head>
        <meta charset="utf-8" />
        <title></title>

        <script>

            function validateMe(){

                document.getElementById("button1").addEventListener("click",validateForm); 

                function validateForm(){
                    //alert("Wheeeeee!");

                    var formy = document.getElementById("testy"); 

                    for (var i = 0; i < formy.length; i++) {
                        if (formy[i].value == "") {
                            document.getElementById("errorMessages").innerHTML = "Please don't leave blank"
                            document.form["testy"].focus();
                            formy[i].style.backgroundColor = "red"; 
                            return false;
                        } 
                        else {
                            formy[i].style.backgroundColor = "#fff"
                        }
                        return true;
                    }


                }   

            }

            window.addEventListener("load",validateMe);

        </script>
    </head>
    <body>

        <form name="" id="testy" action="" onsubmit="return validateMe">
                <p id="errorMessages"></p>
                First Name: <input type="input" name="first_name" id="first_name" />
                <br /><br />
                Last Name: <input type="input" name="last_name" id="last_name" />
                <br /><br />
                Email Address: <input type="input" name="email" id="email" />
                <br /><br />
                <input type="submit" value="Validate" id="button1" />
        </form>

    </body>
</html>

编辑

避免jQuery和HTML5属性验证,因为我正在努力学习JS的细节。

3 个答案:

答案 0 :(得分:1)

以下是使用javascript验证的代码。我想指出一些事情。 首先,你在for循环中添加了return,这样只会检查第一个元素。因为您的条件是真或假,它将始终停止执行它的下一次迭代并将返回。 您还可以使用数组为不同的元素添加错误消息。

<html>
    <head>
        <meta charset="utf-8" />
        <title></title>

    </head>
    <body>

        <form name="" id="testy" action="" >
                <p id="errorMessages"></p>
                First Name: <input class='form-item' type="input" name="first_name" id="first_name" />
                <br /><br />
                Last Name: <input class='form-item' type="input" name="last_name" id="last_name" />
                <br /><br />
                Email Address: <input class='form-item' type="input" name="email" id="email" />
                <br /><br />
                <input type="submit" value="Validate" id="button1" />
        </form>

        <script>

    var form = document.getElementById("testy");

    form.addEventListener("submit", function (e) {
        e.preventDefault();
        var error = [];
        for (var i = 0; i < form.length; i++) {
            if (form[i].value == "") {
                //document.getElementById("errorMessages").innerHTML += "Please don't leave blank<br/>";
                error.push("Please don't leave "+form[i].name+" blank<br/>");
                form[i].focus();
                form[i].style.backgroundColor = "red";                             
            } 
            else {
                form[i].style.backgroundColor = "#fff"
            }                        
        }
        if(error.length){
            document.getElementById("errorMessages").innerHTML = "<ul>";
            for(var i=0; i<error.length;i++){
                document.getElementById("errorMessages").innerHTML += "<li>"+error[i]+"</li>";
            }
            document.getElementById("errorMessages").innerHTML += "</ul>";
        }else{
            form.submit();
        }

    });

    var obj = document.getElementsByClassName("form-item");
    for (var i = 0; i < obj.length; ++i) {
        var item = obj[i];  
        item.onfocus = function(){
            this.style.backgroundColor = "#fff";
        }
    }

        </script>
    </body>
</html>

答案 1 :(得分:0)

尝试使用此代码进行表单验证;

HTML表单

<form name="" id="testy" action="">
        <p id="errorMessages"></p>
        First Name: <input type="input" name="first_name" id="first_name" />
        <br /><br />
        Last Name: <input type="input" name="last_name" id="last_name" />
        <br /><br />
        Email Address: <input type="input" name="email" id="email" />
        <br /><br />
        <input type="submit" value="Validate" id="button1" />
</form>

JQuery脚本

<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script>
  // When the browser is ready...
  jQuery(function($){

    // Setup form validation on the #register-form element
    $("#testy").validate({
        // Specify the validation rules
        rules: {
            first_name: { required: true },
            last_name: { required: true },

            email: {
                required: true,
                email: true
            },
        },

        // Specify the validation error messages
        messages: {
            first_name: "Please enter your first name.",
            last_name: "Please enter your last name.",
            //txtPhone: "Please Enter your Phone No",
            email: {
                required: "Please enter your email.",
                email: "Please enter valid email id"
            }
        },

        submitHandler: function(form) {
            form.formName();
        }
    });

  });

</script>

它是用于表单验证的jQuery验证插件。 (https://jqueryvalidation.org/documentation/

答案 2 :(得分:0)

的document.getElementById(&#34;按钮1&#34)。的addEventListener(&#34;单击&#34;,validateForm);不需要像你在onsubmit =&#34;返回validateForm&#34;中写的那样。同时提交和onclick也不同。

document.form [&#34;暴躁&#34]。对焦();正在生成异常并且您的代码直到声明&#34;返回false&#34;才会到达。替换为document.getElementById(&#34; testy&#34;)。elements [i] .focus(); 你也可以添加一些时间延迟。