返回false但提交

时间:2019-01-23 15:59:51

标签: javascript forms email subscribe

我尝试两种方法来解决此问题

<form method="post">
    <input type="text" id="testId" name="testId" placeholder="Email"  />
    <button id="btnValidate" type="submit" onclick="return check();">subscribe</button>
</form>

其他方法是

<form method="post" onsubmit="return check();">
    <input type="text" id="testId" name="testId" placeholder="Email"  />
    <button id="btnValidate" type="submit">subscribe</button>
</form>

我的js是

 function check() {      

    var email = document.getElementById("testId").value;

    var exptext = /^[A-Za-z0-9_\.\-]+@[A-Za-z0-9\-]+\.[A-Za-z0-9\-]+/;

        if(exptext.test(email)==false){


        alert("error");

        document.addjoin.email.focus();

        return false;

    }else{
        alert("complete");

        return true;            
    }

}

提示显示“错误”,但提交错误的电子邮件。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您只需要删除onclick="return check();"

然后,您只需将document.getElementById("btnValidate").onclick = check;添加到您的js中就可以了

答案 1 :(得分:0)

<form method="post" id="form">
  <input type="text" id="testId" name="testId" placeholder="Email"  />
  <button id="btnValidate" type="submit">subscribe</button>
</form>

<script>
  let form = document.querySelector('#form');
  form.addEventListener('submit', function(e) {
    e.preventDefault();
    check();
  });
</script>
<script>
   function check() {      

    let email = document.getElementById("testId").value;

    let exptext = /^[A-Za-z0-9_\.\-]+@[A-Za-z0-9\-]+\.[A-Za-z0-9\-]+/;

    if(exptext.test(email) === false){

      alert("error");

      document.addjoin.email.focus();

      return false;

    } else {
      alert("complete");

      return true;            
    }

  }

</script>

这应该有效