Categories
JavaScript Answers

How to validate a ISO 8601 date using moment.js?

Spread the love

Sometimes, we want to validate a ISO 8601 date using moment.js.

In this article, we’ll look at how to validate a ISO 8601 date using moment.js.

How to validate a ISO 8601 date using moment.js?

To validate a ISO 8601 date using moment.js, we can use the isValid method.

For instance, we write:

const isValid = moment("2022-10-10T14:48:00", moment.ISO_8601).isValid()
console.log(isValid)

We call moment with the date string to parse and moment.ISO_8601 to parse the date string as an ISO 8601 date string.

Then we call isValid to return whether the date string is a valid date string according to the format we specified when parsing.

Therefore, isValid should be true since we the date string is a valid ISO 8601 date string.

Conclusion

To validate a ISO 8601 date using moment.js, we can use 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 *