Simple Date validation with JavaScript

Just show me the code:

const date = new Date(`${year}-${month}-${day}`)
const isValidDate = (Boolean(+date) && date.getDate().toString() === 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() with date strings on format YYYY-MM-DD or MM/DD/YYYY, and many other ways that you can check on the 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 eighter, 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.

+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 if the Date object returns “Invalid Date”, it is still an object and will take it as a truthy value. NaN on the other hand won’t. I am converting it to a Boolean() just because I believe it gets easier to understand, would not be necessary.

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().toString() === 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.