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

avatar

Borislav Hadzhiev

Last updated: Aug 27, 2022

banner

Photo from Unsplash

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

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

  1. Check if the string passes a regular expression check.
  2. Check if formatting the string as ISO and passing it to the Date constructor returns a valid Date object.
  3. If all of the conditions are met, the string is formatted correctly.
index.js
function dateIsValid(dateStr) { const regex = /^\d{2}\/\d{2}\/\d{4}$/; if (dateStr.match(regex) === null) { return false; } const [day, month, year] = dateStr.split('/'); // 👇️ format Date string as `yyyy-mm-dd` const isoFormattedStr = `${year}-${month}-${day}`; const date = new Date(isoFormattedStr); const timestamp = date.getTime(); if (typeof timestamp !== 'number' || Number.isNaN(timestamp)) { return false; } return date.toISOString().startsWith(isoFormattedStr); } console.log(dateIsValid('18/01/2022')); // 👉️ true console.log(dateIsValid('35/01/2022')); // 👉️ false console.log(dateIsValid('hello')); // 👉️ false

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

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

The regex variable stores a regular expression.

The forward slashes / / mark the beginning and end of the regular expression.

The caret ^ matches the beginning of the input and the dollar sign $ matches 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 forward slashes.

If you ever need help reading a regular expression, check out this regex cheatsheet from MDN.

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 doesn't match the regular expression, we return false from the function.

The next step is to get a string, formatted as YYYY-MM-DD and pass it to the Date() constructor to see if we get a valid Date object back.

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

index.js
function dateIsValid(dateStr) { const regex = /^\d{2}\/\d{2}\/\d{4}$/; if (dateStr.match(regex) === null) { return false; } const [day, month, year] = dateStr.split('/'); // 👇️ format Date string as `yyyy-mm-dd` const isoFormattedStr = `${year}-${month}-${day}`; const date = new Date(isoFormattedStr); 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(isoFormattedStr); } console.log(dateIsValid('35/01/2022')); // 👉️ 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 the 1st of January 1970 and the given date.

In our if condition, we check if the timestamp variable doesn't 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, then the date string is valid and formatted as DD/MM/YYYY.

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.