Question

Is MomentJS intended for user input parsing?

I've got moderately close with the easy cases, having it accept dates in the DDMMYYYY order, and it handles some variation.

It doesn't handle invalid dates particularly well when specifying the format - Including having day values too high, or switching year values between 2 and 4 digit.

Examples of year interpretation:

var date1 = moment('30082012', 'DDMMYYYY');
var date2 = moment('30082012', 'DDMMYY'); // Gives wrong year - 2020
var date3 = moment('300812', 'DDMMYYYY'); // Gives wrong year - 1900
var date4 = moment('300812', 'DDMMYY');

Examples of what would hopefully be invalid dates:

var date5 = moment('08302012', 'DDMMYYYY'); // Gives Jun 08 2014
var date6 = moment('08302012', 'DDMMYY'); // Gives Jun 08 2022
var date7 = moment('083012', 'DDMMYYYY'); // Gives Jun 08 1902
var date8 = moment('083012', 'DDMMYY'); // Jun 08 2014

I have created a JS Fiddle with these examples: http://jsfiddle.net/cHRfg/2/

Is there a way to have moment accept a wider array of user input, and reject invalid dates? Or is the library not intended for this?

Était-ce utile?

La solution

You can try parsing multiple formats. Updated fiddle: http://jsfiddle.net/timrwood/cHRfg/3/

var formats = ['DDMMYYYY', 'DDMMYY'];
var date1 = moment('30082012', formats);
var date4 = moment('300812', formats);

Here are the relevant docs. http://momentjs.com/docs/#/parsing/string-formats/

There is development on adding moment.fn.isValid which will allow you to do validation like in examples 5-8. It will be added in the 1.7.0 release. https://github.com/timrwood/moment/pull/306

Autres conseils

var parsed = moment(myStringDate, 'DD.MM.YYYY');

for Version >= 1.7.0 use:

parsed.isValid()

for Version < 1.7.0 create your own isValid() function:

function isValid(parsed) { 
    return (parsed.format() != 'Invalid date');
}    

checkout the docs: http://momentjs.com/docs/#/parsing/is-valid/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top