Function to Check for Valid Dates

I am looking for a succinct (preferably using regular expressions as much as possible) to validate that two values passed into a function are dates that follow a "MM/DD/YYYY" format, and that the first date is less than or equal to the second date.

basically:

function checkDateRange(date1, date2) {
  // checks to see if date1 is a valid date in "MM/DD/YYYY" format
  // checks to see if date2 is a valid date in "MM/DD/YYYY" format
  // checks to see if date1 is less than date 2
}
LVL 15
DanielSKimAsked:
Who is Participating?
 
mvan01Connect With a Mentor Commented:
Hi Daniel,

See this:  http://Q_20775188.html

Peace and joy.  mvan
0
 
Pravin AsarPrincipal Systems EngineerCommented:
<script language="javascript">
function  isValidDate (inputDate) {
 
  if (inputDate.match (/^[0-1][0-9]\/[0-1][0-9]\/2[0-9][0-9][0-9]/)) {
     alert ('OKAY');
  }
  else {
        alert ('NO OKAY');
  }
}
function checkDateRange(date1, date2) {
   //checks to see if date1 is a valid date in "MM/DD/YYYY" format
   if (!isValidDate (date1)) { return false; }
   // checks to see if date2 is a valid date in "MM/DD/YYYY" format
   if (!isValidDate (date2)) { return false; }
   // checks to see if date1 is less than date 2
   var d1 = new Date (date1);
   var d2 = new Date (date2);
   if (d1 > d2) { alert ('Date 1 greater than Date 2'); }
}

</script>
<form>
<input type="text" name="date1" onBlur="isValidDate(this.value);">
<input type="text" name="date2" onBlur="isValidDate(this.value);">
<input type="button" value="Validate " onclick="checkDateRange(this.form.date1, this.form.date2);">
</form>
0
 
Pravin AsarConnect With a Mentor Principal Systems EngineerCommented:
Take this one, I forgot to add the return statements in isValidDate()


<script language="javascript">
function  isValidDate (inputDate) {
 
  if (inputDate.match (/^[0-1][0-9]\/[0-1][0-9]\/2[0-9][0-9][0-9]/)) {
     alert ('OKAY');
     return true;
  }
  else {
       alert ('NO OKAY');
       return false;
  }

}
function checkDateRange(date1, date2) {
   //checks to see if date1 is a valid date in "MM/DD/YYYY" format
   if (!isValidDate (date1)) { return false; }
   // checks to see if date2 is a valid date in "MM/DD/YYYY" format
   if (!isValidDate (date2)) { return false; }
   // checks to see if date1 is less than date 2
   var d1 = new Date (date1);
   var d2 = new Date (date2);
   if (d1 > d2) { alert ('Date 1 greater than Date 2'); }
}

</script>
<form>
<input type="text" name="date1" onBlur="isValidDate(this.value);">
<input type="text" name="date2" onBlur="isValidDate(this.value);">
<input type="button" value="Validate " onclick="checkDateRange(this.form.date1, this.form.date2);">
</form>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.