Sometimes, we want to prevent "Invalid date" with Moment.js and JavaScript.
In this article, we’ll look at how to prevent "Invalid date" with Moment.js and JavaScript.
How to prevent "Invalid date" with Moment.js and JavaScript?
To prevent "Invalid date" with Moment.js and JavaScript, we can check if a date is valid with the isValid
method.
For instance, we write:
console.log(moment('2022-01-01').isValid())
console.log(moment('abc').isValid())
to create moment objects with a valid and invalid date string.
Then we can call inValid
on each to check if they’re valid dates.
Therefore, the first log should log true
since it’s a valid and the 2nd one should log false
since it’s not.
Conclusion
To prevent "Invalid date" with Moment.js and JavaScript, we can check if a date is valid with the isValid
method.