moment / moment

Parse, validate, manipulate, and display dates in javascript.

Home Page:momentjs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Strict validation is being forgiving

johnstrickler opened this issue · comments

moment('2012-05-25', 'YYYY-MM-DD', true).isValid();        // true
moment('201-05-25', 'YYYY-MM-DD', true).isValid();         // true
moment('20-05-25', 'YYYY-MM-DD', true).isValid();          // true
moment('2-05-25', 'YYYY-MM-DD', true).isValid();           // true

I would expect the last 3 lines to be false.

In the current implementation, the strict parser makes sure that all the tokens are used and they consume all the text, but the tokens themselves are still forgiving. For example, "YYYY" matches 1-4 digits.

@ichernev - you mentioned once that we might want separate token definitions for strict. What do you think?

Well, if we want to move forward from a hacky implementation that sort of works to something better, yes, we do need separate tokens. I'm pretty sure there was a reason why not to use parse -> format -> check for equality, but I can think about one right now.

I just meant having alternative versions of parseTokenFourDigits and company.

FYR: Corresponding jsfiddle

Current workaround:

moment('12/31/2013', 'MM/DD/YYYY', true).isValid() && 
              moment('12/31/2013', 'MM/DD/YYYY').get('y').toString().length == 4;

Comment if there is anything simpler.

Here's an alternative workaround (less robust but simpler):

moment('12/31/2013', 'MM/DD/YYYY', true).isValid()  && /\d{4}$/.test('12/31/2013')