Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...