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;