Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Validate From and To Date using JavaScript

3.00/5 (2 votes)
13 Feb 2012CPOL 15.8K  
I have made some changes in the code and made some user friendly validation and removed extra code and unnecessary conditions, also changed the Regular Expression for date validation. function isValidDate(varFrom, varTo) { var fromdate, todate, dt1, dt2,...

I have made some changes in the code and made some user friendly validation and removed extra code and unnecessary conditions, also changed the Regular Expression for date validation.


JavaScript
<script type="text/javascript">
  function isValidDate(varFrom, varTo) {
    var fromdate, todate, dt1, dt2, mon1, mon2, yr1, yr2, date1, date2;
    var chkFrom = document.getElementById(varFrom);
    var chkTo = document.getElementById(varTo);
    if (varFrom != null && varTo != null) {
      if (checkdate(chkFrom) != true) {
        chkFrom.value = '';
        chkFrom.focus();
        return false;
      }
      else if (checkdate(chkTo) != true) {
        chkTo.value = '';
        chkTo.focus();
        return false;
      }
      else {
        fromdate = chkFrom.value;
        todate = chkTo.value;
        date1 = new Date(fromdate);
        date2 = new Date(todate);

        if (date2 <= date1) {
          alert("To date Should be greater than From date");
          chkFrom.value = '';
          chkFrom.focus();
          return false;
        }
      }
    }
    return true;
  }

  function checkdate(input) {
    var validformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/ //Basic check for format validity
    var returnval = true;
    if (input.value == '' || !validformat.test(input.value))
    {
      alert("Invalid Date Format. Please correct and submit again.")
      var returnval = false;
    }
    return returnval
  }
</script>

Enjoy coding :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)