Validate a Date formatted as YYYY-MM-DD in JavaScript


Borislav Hadzhiev

Last updated: Jan 18, 2022


Check out my new book

Validate a Date formatted as YYYY-MM-DD in JavaScript #

To validate a date that is formatted as YYYY-MM-DD:

  1. Check if the string passes a regular expression check.
  2. Check if passing the string to the Date constructor returns a valid Date object.
  3. If all of the conditions are met, the string is formatted correctly.
function dateIsValid(dateStr) { const regex = /^\d{4}-\d{2}-\d{2}$/; if (dateStr.match(regex) === null) { return false; } const date = new Date(dateStr); const timestamp = date.getTime(); if (typeof timestamp !== 'number' || Number.isNaN(timestamp)) { return false; } return date.toISOString().startsWith(dateStr); } console.log(dateIsValid('2022-01-24')); // 👉️ true console.log(dateIsValid('2022-01-35')); // 👉️ false console.log(dateIsValid('hello')); // 👉️ false

We created a reusable function that checks if a string is a valid date, formatted as YYYY-MM-DD.

The function takes a string in the form of YYYY-MM-DD as a parameter.

The regex variable stores a regular expression.

The forward slashes / / mark the beginning and end of the regex.

The caret ^ matches the beginning of the input and the dollar sign $ - the end of the input.

The \d special character matches any digit in the range of 0 to 9. Specifying the \d character is the same as specifying a range of [0-9].

The number in the curly braces {} is an exact match of the number of digits we expect between the hyphens.

If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.

The String.match method returns an array containing the matches of the regular expression in the string or null if no matches are found.

If the provided string does not match the regular expression, we return false from the function.

The next step is to pass the date string to the Date() constructor to see if we get a valid Date object back.

Here is an example of the flow for when an invalid date that passes the regex is supplied to the dateIsValid function.

function dateIsValid(dateStr) { const regex = /^\d{4}-\d{2}-\d{2}$/; if (dateStr.match(regex) === null) { return false; } const date = new Date(dateStr); console.log(date); // 👉️ Invalid Date const timestamp = date.getTime(); console.log(timestamp); // 👉️ NaN if (typeof timestamp !== 'number' || Number.isNaN(timestamp)) { // 👇️ this runs return false; } return date.toISOString().startsWith(dateStr); } console.log(dateIsValid('2022-01-35')); // 👉️ false

The date variable stores an Invalid Date object.

Calling the getTime() method on the Invalid Date object returns NaN (not a number).

The getTime method returns a number that represents the milliseconds between 1st of January, 1970 and the given date.

In our if condition, we check if the timestamp variable does not store a number or stores NaN.

Unfortunately, if you console.log(typeof NaN), we get back a "number" value back.

The last step is to use the toISOString() method to check if the Date object's ISO 8601 formatted string starts with the provided string.

The toISOString() method returns a string formatted as YYYY-MM-DDTHH:mm:ss.sssZ.

If the ISO representation of the Date object starts with the provided string, we can conclude that the date string is valid and formatted as YYYY-MM-DD.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.