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

[bottomads][/bottomads]

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.