stopping form submit if the validation fails.

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.

<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>

Answers:

Answer

Just a comment:

If your listener passes a reference to the form, you can access the controls by name or 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;
}
Answer

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>
Answer

use return on the onclick attribute in the form tag attribute onsubmit="return validateForm()" , 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!

<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>

Answer

return is not going to stop the form from submit if its called in a subfunction e.g. 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();

}
Answer

In my case i used pattern in input field and also gave maxlength.

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

Answer
     -    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>
Answer

you can achieve the same thing using jQuery Form Plugin.

$(document).ready(function() { 

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.