moment.js isValid function not working properly

103,659

Solution 1

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);

Solution 2

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/

Share:
103,659

Related videos on Youtube

Mikel Sanchez
Author by

Mikel Sanchez

Mobile Developer always learning!

Updated on October 11, 2020

Comments

  • Mikel Sanchez
    Mikel Sanchez over 3 years

    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/

    • scunliffe
      scunliffe over 10 years
      I can only guess that they explicitly test that the format you pass is tested... but there's no check for "is value the same length as format?"... I'd suggest to try submitting a bug report to moment.js
    • Mathletics
      Mathletics over 10 years
      ...why do you have those extra characters in the first place? Does it correctly validate longer date-strings against that format?
    • Mikel Sanchez
      Mikel Sanchez over 10 years
      what do you mean with extra characters?
  • Mikel Sanchez
    Mikel Sanchez over 10 years
    true (index):26 true (index):27 true (index):29 This is the console log output :S
  • Jan Sommer
    Jan Sommer over 10 years
    If you check your jsfiddle, you'll notice that you are NOT passing true as a third argument anywhere, but in your question you state that moment('03:55jojojo', 'HH:mm',true).isValid(); returns true. Please run that exact code in your browser - the output is false.
  • Kentonbmax
    Kentonbmax about 6 years
    moment('13/13/2000').isValid() returns true. You must include the format designation for it to validate properly.