Date Range Validation in JavaScript ES5 and One-Liner ES6

Snippet to validate a date range where the start date cannot be greater than the end date in JavaScript, the ES5 way and the better one-liner ES6 way.

ES5

var dateRangeValidatorES5 = function (start, end) {
  if (Date.parse(start) < Date.parse(end) || start === end) {
    return true;
  }

  return false;
};

if(dateRangeValidatorES5('4/15/17','4/20/17')) {
  console.log('valid');
} else {
  console.log('invalid');
}

// Output: valid

ES6

const dateRangeValidatorES6 = (start, end) => (Date.parse(start) < Date.parse(end) || start === end) ? true : false;

if(dateRangeValidatorES6('4/25/17','4/20/17')) {
  console.log('valid');
} else {
  console.log('invalid');
}

// Output: invalid

Play with this snippet in CodePen

 

Esau Silva
Software Engineer at Region One ESC
Full Stack Software Engineer working with Microsoft technologies, ReactJS is awesome and avid Brazilian Jiu-Jitsu practitioner
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed.
Share