Validate a date in JavaScript

If you have to validate a date coming from an HTML widget (year, month, day <select> elements or a date picker), or any other input, you still have to make sure that the date being processed is valid.

Validation here means that "December 0, 2019" and "December -1, 2019" are invalid, as well as "February 30", "February 31", "April 31" or "September 35, 2022", as well as "February 29, 2022", but not "February 29, 2020".

The timestamp behind the datetime is a Unix integer.

  • "December 0, 2019" becomes "November 30, 2019"
    • because the timestamp of "December 0, 2019" is the integer of "November 30, 2019".
  • "December -1, 2019" becomes "November 29, 2019".
  • "February 30, 2022" becomes "March 2, 2022".
  • "February 31, 2022" becomes "March 3, 2022".
  • "April 31, 2022" becomes "May 1, 2022".
  • "September 35, 2022" becomes "October 5, 2022".

Even if you create dynamic validators for your date picker to prevent certain values to be entered in the widget, you still should check the value before it goes in the HTTP response.

Code

We check if the month of the provided datetime is the same as from a new Date object that creates automatically a valid timestamp integer to check against.

The curveball here is that in JavaScript, the month argument of a Date object is in a zero-based array format: 0 = January, 11 = December. But we make adjustments (-1, +1) to the Date object to provide a normal month number: 1 = January, 12 = December.

Put this in your JavaScript code:

function isValidDate(year, month, day) {
    var d = new Date(year, month - 1, day);
    return month == d.getMonth() + 1;
}

Result

Boolean is returned.

isValidDate(2019, 12, 0);  //=> false
isValidDate(2019, 12, -1); //=> false
isValidDate(2020, 2, 29);  //=> true
isValidDate(2021, 2, 29);  //=> false
isValidDate(2022, 2, 30);  //=> false
isValidDate(2022, 2, 31);  //=> false
isValidDate(2022, 4, 31);  //=> false
isValidDate(2022, 9, 35);  //=> false