Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to validate time using Moment JS?

Tags:

momentjs

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.

like image 601
Chiranjib Avatar asked Sep 25 '14 13:09

Chiranjib


People also ask

How do you validate time in a moment?

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.

What is the replacement for MomentJS?

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.

Can we still use MomentJS?

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.

What is Moment () in JavaScript?

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.


1 Answers

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
like image 67
Matt Johnson-Pint Avatar answered Nov 15 '22 18:11

Matt Johnson-Pint