简体   繁体   English

验证失败时阻止表单提交

[英]Preventing from form submission when validation fails

How do I prevent this from submission when validation fails? 验证失败时,如何防止提交此问题? I don't know what to put in the validateForm function... I have this form: 我不知道要在validateForm函数中放什么...我有这种形式:

<form action="ChangePassword" method="POST">  
    <input type="submit" value="Change Password" onclick="validateForm();"/>
</form>

And the validateform function: validateform函数:

<script>
    function validateForm() {
        if(document.getElementById("passError").innerHTML !== "") {
            alert("There are some errors.");
            return false;
        }
    }
</script>

You need to return from your event handler function. 您需要从事件处理函数中返回。

You are currently only returning from validateForm which is a function you call from your event handler function. 当前,您仅从validateForm返回,后者是事件处理函数调用的函数。

onclick="return validateForm();"

Good practise would be: 好的做法是:

  • to perform the check when it is submitted rather then only when the submit button is clicked (ie use onsubmit on the form instead of onclick on the button). 在提交时执行检查,而不是仅在单击提交按钮时执行检查(即,在表单上使用onsubmit而不是在按钮上onclick )。
  • to bind your event handlers with JavaScript instead of depending on globals and intrinsic event attributes 使用JavaScript绑定事件处理程序,而不是依赖于全局变量和内部事件属性

Maybe you have to stop the bubbling from your scope with e.preventDefault() instead of return false ? 也许您必须使用e.preventDefault()停止从作用域冒泡,而不是返回false?

    function validateForm(event) {
    if(document.getElementById("passError").innerHTML !== "") {
        alert("There are some errors.");
        event.preventDefault();
    }
}

You have to do it in your form. 您必须以表格形式进行。 Not in submit button. 不在提交按钮中。 Like: 喜欢:

<form name="myForm" onsubmit="return validateForm();"> 

And also return true if your validation passes in your validate function. 如果验证通过了validate函数,则还返回true

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

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