Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js isValid function not working properly

I have this question... I haven't found anything similar and it also seems very strange that nobody had this problem validating time with moment.js.

moment('03:55', 'HH:mm').isValid(); //true
moment('03:55jojojo', 'HH:mm').isValid(); //true
moment('03:55jojojo', 'HH:mm',true).isValid(); //true

Am I doing something wrong? Here is an example:

http://jsfiddle.net/vCGAp/145/

like image 368
Mikel Sanchez Avatar asked Nov 14 '13 13:11

Mikel Sanchez


People also ask

How do you check if a date is valid in moment?

isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.

Why use MomentJS?

Moment. js is a stand-alone open-source JavaScript framework wrapper for date objects that eliminates native JavaScript date objects, which are cumbersome to use. Moment. js makes dates and time easy to display, format, parse, validate, and manipulate using a clean and concise API.

How to use MomentJS library?

You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm. In MomentJS, you can find many easy to use methods to add, subtract, validate date, get the maximum, minimum date etc.


2 Answers

In your question you write that moment('03:55jojojo', 'HH:mm',true).isValid(); returns true. This is incorrect. Please check your jsfiddle again.

From http://momentjs.com/docs/

Moment's parser is very forgiving, and this can lead to undesired behavior. As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly.

moment('It is 2012-05-25', 'YYYY-MM-DD').isValid();        // true
moment('It is 2012-05-25', 'YYYY-MM-DD', true).isValid();  // false
moment('2012-05-25', 'YYYY-MM-DD', true).isValid();        // true

You can use both language and strictness.

moment('2012-10-14', 'YYYY-MM-DD', 'fr', true);
like image 160
Jan Sommer Avatar answered Oct 09 '22 05:10

Jan Sommer


Sorry to necro this 5 year old question, but I indeed stumbled upon a case where monent is not working properly towards the documentation, using version 2.24.0.

Formats

In the picture we can see that for example H should only evaluate to 0 - 23, but if I use moment('01', 'H', true).isValid() I still get true.

Here is the jsfiddle: https://jsfiddle.net/wofgst5v/

like image 2
knnhcn Avatar answered Oct 09 '22 05:10

knnhcn