Skip to main content Accessibility Feedback

How to check if a date is valid with vanilla JavaScript

While working on a form validation project recently, I needed a way to validate if a date was actually valid or not.

For example, March 30 is a real date, but February 30 doesn’t exist. February 29 exists only on leap years. I stumbled upon this set of JavaScript methods that validates dates (including checking for leap years).

/**
 * Get the number of days in any particular month
 * @link https://stackoverflow.com/a/1433119/1293256
 * @param  {integer} m The month (valid: 0-11)
 * @param  {integer} y The year
 * @return {integer}   The number of days in the month
 */
var daysInMonth = function (m, y) {
    switch (m) {
        case 1 :
            return (y % 4 == 0 && y % 100) || y % 400 == 0 ? 29 : 28;
        case 8 : case 3 : case 5 : case 10 :
            return 30;
        default :
            return 31
    }
};

/**
 * Check if a date is valid
 * @link https://stackoverflow.com/a/1433119/1293256
 * @param  {[type]}  d The day
 * @param  {[type]}  m The month
 * @param  {[type]}  y The year
 * @return {Boolean}   Returns true if valid
 */
var isValidDate = function (d, m, y) {
    m = parseInt(m, 10) - 1;
    return m >= 0 && m < 12 && d > 0 && d <= daysInMonth(m, y);
};

To use it, call isValidDate() with your day, month, and year as arguments. It uses the daysInMonth() helper method to check if your day actually exists in that month in that particular year.

For example…

isValidDate(30, 3, 2017); // March 30, 2017 - true
isValidDate(29, 2, 2017); // February 29, 2017 - false
isValidDate(29, 2, 2016); // February 29, 2016 - true

🔥 Hot off the press! I just launched a new pocket guide. Learn how to build interactive web apps with vanilla JavaScript.

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips