Just show me the code:
const date = new Date(year, (+month-1), day)
const isValidDate = (Boolean(+date) && date.getDate() == day)
What is that?
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
+month?? +date ??? Are you adding a date?
(+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
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.