Categories
JavaScript Answers

How to prevent “Invalid date” with Moment.js and JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *