Monday, November 9, 2015

Date validation From and To using JavaScript


varFrom - ID of Form date control
varTo - ID of To date control


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
  } 

No comments:

Post a Comment