Html 如果验证失败,则停止表单提交。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17646471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:09:14  来源:igfitidea点击:

stopping form submit if the validation fails.

javascripthtml

提问by user2581072

I am validating the dates in below function. If the validation fails, then the form should not get submitted. I tried returning false in form onsubmit but it still gets submitted. However, Validation is working fine and getting the alert that I put in the function. Any help to stop submitting the form if validation fails.

我正在验证以下函数中的日期。如果验证失败,则不应提交表单。我尝试在提交时以表单返回 false,但它仍然被提交。但是,验证工作正常并收到我放入函数的警报。如果验证失败,任何帮助停止提交表单。

<script>
  function dateCheck()
  {
      start = document.getElementById('name3').value;
      end = document.getElementById('name4').value;
      compare(start, end);
      document.getElementById('name4').focus();

  }

  function compare(sDate, eDate)
  {

      function parseDate(input) {
            var parts = input.match(/(\d+)/g);

            return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
          }
       var parse_sDate = parseDate(sDate);
      var parse_eDate = parseDate(eDate);
       parse_sDate.setFullYear(parse_sDate.getFullYear() + 1);

      if(parse_eDate >= parse_sDate)
          {
          alert("End date should not be greater than one year from start date");
           return false;
          }
       return true;
  }

</script>
</head>
<body>
<form onsubmit="return dateCheck()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly"> 
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
 <td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
 <img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
 </tr>
</table>
<input type="submit" value="Submit">
</form>

回答by RobG

Just a comment:

只是评论:

If your listener passes a reference to the form, you can access the controls by name or ID:

如果您的侦听器传递对表单的引用,您可以按名称或 ID 访问控件:

<form onsubmit="return dateCheck(this)">

then:

然后:

function dateCheck(form) {
  var start = form.name3.value;
  ...
}

Note that you should declare variables, otherwise they will become global at the point they are assigned to. Also, you should check the values in the controls before passing them to the compare function (and display a message asking the user to enter a valid value if they aren't).

请注意,您应该声明变量,否则它们将在分配给它们时成为全局变量。此外,您应该在将控件中的值传递给比较函数之前检查它们(如果不是,则显示一条消息,要求用户输入有效值)。

function dateCheck(form) {
  var start = form.name3.value;
  var end = form.name4.value;
  var valid = compare(start, end);

  if (!valid) form.name4.focus();

  return false;
}

回答by Olu Adabonyan

I appreciate all contributions above. I have just applied the suggestions above to solve my challenge & it works fine. Keeping it simple I use the following:

我感谢上面的所有贡献。我刚刚应用了上面的建议来解决我的挑战,而且效果很好。保持简单,我使用以下内容:

<form id="newuser" action="newuser.php" onsubmit="return pswderr(this)">

For the button I have

对于我有的按钮

<input id='submit' type="submit" value="Login" onClick="return pswderr();">

My script is:

我的脚本是:

<script>
function pswderr() {
    var pswd1 = document.getElementById("newuserpswd").value;
    var pswd2 = document.getElementById("rptpswd").value;
    if (pswd1 !== pswd2) {
        document.getElementById("alarm").innerHTML = "Password and password  
        verification do not match. Retry";
        return false;
    } else {document.getElementById("alarm").innerHTML = "";
        return true;
        }
}
</script>

回答by Roshan Jafri

use return on the onclick attribute in the form tag attribute onsubmit="returnvalidateForm()" , if you return false in your validation function in javascript if the input is incorrect then you have to add return to your onclick attribute in order for it to execute .Hope it helped someone!

在表单标记属性 onsubmit=" returnvalidateForm()" 中的 onclick 属性上使用 return ,如果您在 javascript 中的验证函数中返回 false 如果输入不正确,那么您必须将 return 添加到您的 onclick 属性以便它执行。希望它对某人有所帮助!

<script>
        function validateForm(){
            var validation = false;
            var phonenumber = document.forms["enqueryForm"]["phonenumber"].value;
            if(phonenumber != 11) {
                alert("phonenumber is incorrect");
                //e.preventDefault();
                return false;
    
            }
        }
</script>
<form class="form-style-5" action="BookingForm.php" method="post" id="bookingForm" onsubmit="return validateForm()" name="enqueryForm">
<input type="tel" name="phonenumber" placeholder="your no.">
<input type="submit" name="submit" value="submit">
</form>

回答by Sonu patel

     -    I hope this will help you : Just write this code on your Html/jsp page 
    <html>
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            </head>

         - **Don't forget to add this on your html page**

            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

            <script type='text/javascript'>
                $(document).ready(function() {
                    //option A
                    $("regF").submit(function(e) { //regF is form id
                        alert('submit intercepted');
                        e.preventDefault(e);
                    });
                });
            </script>
</html>

回答by Jay Harris

returnis not going to stop the form from submit if its called in a subfunction e.g. compare(sDate, eDate)

return如果它在子函数中调用,则不会阻止表单提交,例如 compare(sDate, eDate)

so change your function to this

所以把你的功能改成这个

function dateCheck(e){

  var start = document.getElementById('name3').value;
  var end = document.getElementById('name4').value;
  if(compare(start, end)) {
    // no error submit i guess
    // return true ?
  } else {
    // error with date compare
    return false;
  }
  end.focus();

}

回答by MD Shahrouq

In my case i used patternin inputfield and also gave maxlength.

就我而言,我在输入字段中使用了模式,并给出了maxlength

What worked with me was, remove Length attribute from input field

对我有用的是,从输入字段中删除 Length 属性

回答by wizzardz

you can achieve the same thing using jQuery Form Plugin.

您可以使用jQuery Form Plugin实现相同的功能。

$(document).ready(function() { 

    $('#your_form_id').ajaxForm( { beforeSubmit: dateCheck } ); 
});