Categories
JavaScript Answers

How to fix moment.js isValid function not working properly with JavaScript?

Spread the love

Sometimes, we want to fix moment.js isValid function not working properly with JavaScript.

In this article, we’ll look at how to fix moment.js isValid function not working properly with JavaScript.

How to fix moment.js isValid function not working properly with JavaScript?

To fix moment.js isValid function not working properly with JavaScript, we can enable strict validation.

For instance, we write

const isValid = moment("It is 2022-05-25", "YYYY-MM-DD").isValid();
const isValid2 = moment("It is 2022-05-25", "YYYY-MM-DD", true).isValid();

to call moment with true as the 3rd argument so that isValid will make sure the date string in the first argument of moment exactly follows the format specified in the string in the 2nd argument.

Therefore, isValid is true, but isValid2 is false since the date string doesn’t exactly follow the YYYY-MM-DD format.

Conclusion

To fix moment.js isValid function not working properly with JavaScript, we can enable strict validation.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.