JS表单验证,如果所有字段都正确则激活提交按钮

时间:2015-01-03 13:59:39

标签: javascript html forms validation

我在JS表单验证方面遇到了麻烦。我使用正则表达式。如果所有字段用户填写正确,则表单中的提交按钮处于活动状态(onmouseover),但当其中一个字段不正确时,将禁用提交按钮。当用户填写所有字段正确 - 提交按钮仍然禁用时,您可以帮我解决这个问题吗?因此,用户必须启用所有字段和提交按钮。

<!-- validation -->
<script language=JavaScript>

    function checkForm() {

    var err = 0;

    if (document.getElementById("fio").value == '') {
        document.getElementById("fio").style.border = "1px solid #FF0000";
        document.getElementById("fio_err").innerHTML = "Enter data";
        err = 1;
    }

    if (document.getElementById("_phone_top").value.length < 5) {
        document.getElementById("_phone_top").style.border = "1px solid #FF0000";
        document.getElementById("tel_err").innerHTML = "length < 5";
        err = 1;
    }

    var email = document.getElementById('email').value;
    emailTest = "^[_.0-9a-z-]+@([0-9a-z][0-9a-z_-]+.)+[a-z]{2,4}$";
    var regex = new RegExp(emailTest); 

    if (!regex.test(email)) {
        document.getElementById("email").style.border = "1px solid #FF0000";
        document.getElementById("email_err").innerHTML = "invalid e-mail";
        err = 1;
    }

    if ( err == 1 ) {
       document.getElementById('ok').setAttribute("disabled","disabled");
    } else {
       document.getElementById('ok').removeAttribute("disabled");
    }    
}

function setBorder(id) {

    document.getElementById(id).style.border = "1px solid #C0C0C0";
    document.getElementById(id+"_err").innerHTML = "";

}
</script>

<!-- Form -->
<form method="post" id="form_top" name="form_top" action="/mail.php">
    <input type="text" class="textbox" name="fio" id="fio" placeholder="NAME"><div id="fio_err"></div><br><br>
    <input type="text" class="textbox" name="tel" id="_phone_top" placeholder="PHONE"><div id="tel_err"></div><br><br>
    <input type="text" class="textbox" name="email" id="email" placeholder="E-Mail"><div id="email_err"></div><br><br>
    <input type="text" class="textbox" name="company" placeholder="COMP"><br><br>
    <input type="text" name="formfrom" value="верхняя форма" hidden>
    <input type="submit" class="textbox" name="ok" id="ok" value="Submit!" onmouseover="checkForm()"><br>
</form>

2 个答案:

答案 0 :(得分:0)

谢谢,禁用按钮不支持触发器onmouseover。 我尝试在每个用户字段上使用onblur触发器,它完美地工作!

答案 1 :(得分:-1)

禁用的输入按钮不会触发onmouseover:http://jsfiddle.net/djwasp4o/如果您手动从html中删除disabled属性,则会触发该事件。

此时,您将禁用该事件:

document.getElementById('ok').setAttribute("disabled", "disabled");

供参考,请参阅:Fire onmouseover event when element is disabled