(JS) Validate date in format YYYY-MM-DD

By | May 13, 2020

A simple JS function to validate that a date string in the format YYYY-MM-DD is a valid date. Will validate that the day is correct for the given month, including leap years

/**
* Validate that a date string in the format YYYY-MM-DD is a valid date
* @param dateString (YYYY-MM-DD)
* @returns {boolean}
*/
function isValidDate(dateString) {

        // Date format: YYYY-MM-DD
        var datePattern = /^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/;

        // Check if the date string format is a match
        var matchArray = dateString.match(datePattern);
        if (matchArray == null) {
            return false;
        }

        // Remove any non digit characters
        var cleanDateString = dateString.replace(/\D/g, ''); 

        // Parse integer values from date string
        var year = parseInt(cleanDateString.substr(0, 4));
        var month = parseInt(cleanDateString.substr(4, 2));
        var day = parseInt(cleanDateString.substr(6, 2));
      
        // Define number of days per month
        var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        // Adjust for leap years
        if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
            daysInMonth[1] = 29;
        }

        // check month and day range
        if (month < 1 || month > 12 || day < 1 || day > daysInMonth[month - 1]) {
            return false;
        }

        // You made it through!
        return true;
    }

3 thoughts on “(JS) Validate date in format YYYY-MM-DD

  1. gabesz

    Nice work!

    A little improvement would be to add ‘$’ to the end of ‘datePattern’. That way ‘2021-02-1912334’ would be invalid after regex comparison.

    Reply

Leave a Reply to Christoffer Wadensten Cancel reply

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