Nahuel Leiva
Nahuel Leiva

Reputation: 117

Validate a non existing date with moment js

Good day to everyone.

I need to validate a non-existing date with moment taking the value from a datepicker, so far I couldn't do it. For example:

moment('29/02/2021').isValid()

will return true as the format is correct but the date as is does not exist... The point with this is to show to the user an error message whenever the value passed to the datepicker is an invalid date or whatever else that is not a date (123456789 or asd for example)

Thank you for your help in advance

Upvotes: 1

Views: 255

Answers (1)

Nahuel Leiva
Nahuel Leiva

Reputation: 117

The answer was pretty simple in the end. Adding the 'L' parameter to the moment date constructor was enough to check if the incoming date exists or not.

Now if you do moment('29/02/2021', 'L').isValid() will return false instead of true, this also checks for the user's locale and will apply the corresponding format.

Upvotes: 1

Related Questions