Simple Date validation with JavaScript
Just show me the code:
const date = new Date(year, (+month-1), day)
const isValidDate = (Boolean(+date) && date.getDate() == day)
What is that?
new Date()
You are probably familiar with the Date Object. So just a very quick recap, you can call new Date()
(MDN Documentation).
If it is not a valid date it will return Invalid Date
— it is not a String
, but it is Not a Number either, so that is good, you could kind of check isNaN(date)
.
The problem is that it will take dates like “2017–02–30” and transform to “2017–03–01”. Smart Javascript? Maybe.
+month?? +date ??? Are you adding a date?
That is the Unary Plus. It will try to convert whatever comes after it to a number and sometimes will just say it is NaN.
So, for (+month -1)
, we are making sure month
is a number and decreasing 1 unit, given that new Date
start counting months from 0.
Furthermore, if the Date
object returns Invalid Date
, it is still an object and the if
condition will be a truthy result.
NaN
, on the other hand, won’t. At this moment I’m converting it to a boolean
value just because I find it easier to understand.
The tricky part
Considering the Date Object does not tell me “2017–02–30” is an incorrect date, we just need to check if the date it says it is now is the same as the one we said.
date.getDate() == day
Easy Peasy
I decided to write this article because you google about it you will find some functions with 10+ lines and pretty manual testings. Those do not look so clean on the code.
Also, because we do not need Moment.js just for that.