如果表单未经过验证,如何停止表单提交

时间:2015-07-26 18:37:40

标签: javascript jquery html jquery-validate

我正在使用jquery验证表单,但问题是表单是否经过验证,无论表单是否经过验证,都会被提交。我想要 当表单被验证时是否存在某些错误(例如空字段),则表单不得提交。请帮助解决我的问题。

<body>
    <script type="text/javascript">
    $(document).ready(function() {
      $("#login_user").validate({
              rules: {
                txtemail: {
                  required: true
                },
                txtpassword: {
                  required: true
                }
              },
              messages: {
                txtemail: {
                  required: "Please enter Username or Email Address"
                },
                txtpassword: {
                  required: "Please enter Password"
                }
              }
      });
    });
    </script>

    <form name="login_user" id="login_user" action="index.php" method="post">
    <input name="txtemail" type="text" placeholder="Username"/> 
    <input name="txtpassword" type="password" placeholder="Password"/>  
    <a id="submit" onclick='document.forms["login_user"].submit(); return false;'>Login</a>

    </body>

2 个答案:

答案 0 :(得分:1)

更改

 <a id="submit" onclick='document.forms["login_user"].submit(); return false;'>Login</a>

 <input type="submit" value="Login" />

并关闭表单标记

<form name="login_user" id="login_user" action="index.php" method="post">
    <input name="txtemail" type="text" placeholder="Username"/> 
    <input name="txtpassword" type="password" placeholder="Password"/>  
    <input type="submit"  value="Login" />
</form>

答案 1 :(得分:-2)

添加e.preventDefault()

$(document).ready(function() {
   $('#login_user').on('submit', function(e) {
      e.preventDefault();
      //do validation and if validation passes
      $('#login_user').submit();
  });
});