Javascript – Using Javascript, how to make sure a date range is valid


In JavaScript, what is the best way to determine if a date provided falls within a valid range?

An example of this might be checking to see if the user input requestedDate is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.

Best Answer

This is actually a problem that I have seen come up before a lot in my works and the following bit of code is my answer to the problem.

// checkDateRange - Checks to ensure that the values entered are dates and 
//     are of a valid range. By this, the dates must be no more than the 
//     built-in number of days appart.
function checkDateRange(start, end) {
   // Parse the entries
   var startDate = Date.parse(start);
   var endDate = Date.parse(end);
   // Make sure they are valid
    if (isNaN(startDate)) {
      alert("The start date provided is not valid, please enter a valid date.");
      return false;
   if (isNaN(endDate)) {
       alert("The end date provided is not valid, please enter a valid date.");
       return false;
   // Check the date range, 86400000 is the number of milliseconds in one day
   var difference = (endDate - startDate) / (86400000 * 7);
   if (difference < 0) {
       alert("The start date must come before the end date.");
       return false;
   if (difference <= 1) {
       alert("The range must be at least seven days apart.");
       return false;
   return true;

Now a couple things to note about this code, the Date.parse function should work for most input types, but has been known to have issues with some formats such as "YYYY MM DD" so you should test that before using it. However, I seem to recall that most browsers will interpret the date string given to Date.parse based upon the computers region settings.

Also, the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven.