【问题标题】:Form Validation Works But Still Submits When User Input The Wrong Answer表单验证有效,但当用户输入错误答案时仍然提交
【发布时间】:2021-12-07 23:25:09
【问题描述】:

我在提交之前编写了一个 Javascript 来验证我的表单。 Javascript 的功能是防止我的表单在用户提供的电话号码与我的 Javascript 中的结果匹配但显示一条错误消息“电话号码已使用!”时自行提交。

我的问题是验证工作正常:用户收到他们提供的电话号码已被使用的警报,但我的表单在显示错误消息后仍会自行提交。

我做错了什么?

下面是我的代码。

function check(form) /*function to check used phone number*/ {
    /*the following code checkes whether the entered phone number is matching*/

  if (form.phonenum.value == "0807575566464" 
|| form.phonenum.value == "09057487463") 
{
    alert("Phone number used! provide a new one! \n") /*displays error message*/
} else if (form.phonenum.value.length<11 || form.phonenum.value.length>11) { alert("Phone number should be 11 digits! \nAnd it should begin with; 080, 081, 070, 090, or 091.");
} 
else {
    return false;
  }

 
}
<form action='' method='POST' enctype="multipart/form-data" id="formName">
  <input type="text" id="phonenum" name="myinput">
  <button href='/' type='submit' onclick="check(this.form)">Submit</button>
</form>

【问题讨论】:

标签: javascript html forms validation


【解决方案1】:

我认为您需要添加 e.preventDefault() 才能在您点击提交时停止重新加载页面。

【讨论】:

    【解决方案2】:

    您需要将一个函数绑定到 onsubmit 事件,如果验证失败则停止该事件。

    HTML:

    <form action='' method='POST' enctype="multipart/form-data" id="formName" onsubmit="validateForm(event)">
    

    JavaScript:

    function validateForm(event) {
      if(validation fails...) {
        event.preventDefault();
        ....
      }
    }
    

    preventDefault 函数的文档和示例: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

    除了使用 event.preventDefault() 你也可以只返回 false:

    https://stackoverflow.com/a/65538474/9441244

    在您的情况下,您的 JavaScript 应该如下所示

    HTML:

    <form action='/test/' method='POST' enctype="multipart/form-data" id="formName" onsubmit="validateForm(event)">
      <input type="text" id="phonenum" name="myinput">
      <button href='/' type='submit'>Submit</button>
    </form>
    

    JavaScript:

    function validateForm(event) {
        if (this.phonenum.value == "0807575566464" || this.phonenum.value == "09057487463") {
            event.preventDefault();
            alert("Phone number used! provide a new one! \n");
        } else if (this.phonenum.value.length != 11) { 
            this.preventDefault();
            alert("Phone number should be 11 digits! \nAnd it should begin with; 080, 081, 070, 090, or 091.");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      相关资源
      最近更新 更多