验证失败时防止表单提交 [英] Preventing from form submission when validation fails

查看:97
本文介绍了验证失败时防止表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

验证失败时如何防止提交此内容?我不知道在 validateForm 函数中输入什么...我有这样的表格:

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:

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

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.

您目前只从 validateForm 返回,这是您从事件中调用的函数处理函数。

You are currently only returning from validateForm which is a function you call from your event handler function.

onclick="return validateForm();"

良好做法是:


  • 在提交时执行检查,而不是仅在单击提交按钮时(即在表单上使用 onsubmit 而不是按钮上的onclick 。

  • 使用JavaScript绑定事件处理程序,而不是依赖于全局变量和内部事件属性

  • to perform the check when it is submitted rather then only when the submit button is clicked (i.e. use onsubmit on the form instead of onclick on the button).
  • to bind your event handlers with JavaScript instead of depending on globals and intrinsic event attributes

这篇关于验证失败时防止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆