Is there a way to validate if the String passed as time is valid using Moment JS?
The operations moment("2014-12-13 asdasd","YYYY-MM-DD LT").isValid()
or moment("asdasd","LT").isValid()
equate to true
which ideally shouldn't happen.
My application uses multiple languages and it is really not possible for me to come up with a RegEx pattern to validate the string. For example, if I get the time string as "午前12時12分0秒"
, Moment JS should be able to validate this. I checked the source and found that time checking is not that strict in the library. I might have missed something. Please help.
Is there a way to validate if the String passed as time is valid using Moment JS? The operations moment("2014-12-13 asdasd","YYYY-MM-DD LT"). isValid() or moment("asdasd","LT"). isValid() equate to true which ideally shouldn't happen.
There are several libraries out there that can potentially replace Moment in your app. The creators of Moment recommend looking into Luxon, Day. js, date-fns, js-Joda, or even replacing Moment with native JS.
Just for info, moment. js is not maintained anymore. If you start a new project don't use moment. But if it's an old project, still use it.
Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.
As described in the documentation, as of moment 2.3.0, you can pass a third parameter true
which turns on "strict parsing" mode.
moment("2014-12-13 asdasd","YYYY-MM-DD LT", true).isValid() // false
moment("2014-12-13 12:34 PM","YYYY-MM-DD LT", true).isValid() // true
The down side is that it must match the locale's format (i.e. the one supplied as the second argument) exactly. Since LT
is equivalent to h:mm A
in English, it will only accept 12-hour time without seconds. If you pass 24 hour time, or pass seconds, then it will fail.
moment("2014-12-13 12:34:00 PM","YYYY-MM-DD LT", true).isValid() // false
moment("2014-12-13 15:00","YYYY-MM-DD LT", true).isValid() // false
A better solution might be to pass multiple formats with strict parsing:
var formats = ["YYYY-MM-DD LT","YYYY-MM-DD h:mm:ss A","YYYY-MM-DD HH:mm:ss","YYYY-MM-DD HH:mm"];
moment("2014-12-13 12:34 PM", formats, true).isValid() // true
moment("2014-12-13 15:00", formats, true).isValid() // true
moment("2014-12-13 12:34:00 PM", formats, true).isValid() // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With