Borislav Hadzhiev
Tue Jan 18 2022·3 min read
Photo by Aki Tolentino
To validate a date that is formatted as DD/MM/YYYY
:
Date
constructor returns a valid Date
object.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 regex.
^
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 forward slashes.
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.
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 for when an invalid date that passes the regex
is supplied to the dateIsValid
function.
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 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.
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 DD/MM/YYYY
.