Search code examples
javascriptangularmomentjsangular-moment

why the date format is not giving correct value?


I am checking whether the date format is valid of not .why this format is valid ?

  alert(moment('16-jun-199', 'DD-MMM-YYYY').isValid())

Why it is giving me true .It should be false .why ? here is my code

http://plnkr.co/edit/ZH2kjC9QWwbdLwmvH2Tp?p=preview where i am doing wrong .formate should be 'DD-MMM-YYYY'


Solution

  • You can try this

    moment('16-jun-199', 'DD-MMM-YYYY',true).isValid())
    

    Note: additional true flag for strict parsing. which tells moment to not to use wildcards and use exact match.

    Moment's parser is very forgiving, and this can lead to undesired/unexpected behavior.

    For example, the following behavior can be observed:

     moment('2016 is a date', 'YYYY-MM-DD').isValid() //true, 2016 was
     matched
    

    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, including delimeters.

    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
    moment('2012.05.25',       'YYYY-MM-DD', true).isValid(); // false
    

    Source:https://momentjs.com/docs/