How to Validate Date Input in JavaScript

A Date instance can be created in JavaScript by passing the date time string as the parameter in yyyy-mm-dd format as in Date(“2015-01-31”). There’s something important to note here though.

If you pass an invalid date string, the Date instance would still be created. For instance, “2015-02-30” is not a valid date but the Date instance would still be created. The date will however be adjust to point to the next logical date and in this case, our Date will be set as “2015-03-02”.

Thus you’ll have to verify the month, year and day of a Date separately to detect an invalid date. A regex is not enough.

function isValidDate(str) {
  // mm-dd-yyyy hh:mm:ss

  var regex = /(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})\s*(\d{0,2}):?(\d{0,2}):?(\d{0,2})/,
    parts = regex.exec(str);

  if (parts) {
    var date = new Date(+parts[3], +parts[1] - 1, +parts[2], +parts[4], +parts[5], +parts[6]);
    if (date.getDate() == parts[2] && date.getMonth() == parts[1] - 1 && date.getFullYear() == parts[3]) {
      return date;
    }
  }

  return false;
}

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻