MomentJS - Designed to validate input?

Is MomentJS designed to parse user input?

I'm moderately close to simple cases where it takes dates in the DDMMYYYY order and handles some options.

It does not handle invalid dates especially well when specifying a format — including too high day values ​​or year values ​​for switching between 2 and 4 digits.

Examples of annual 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 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 created JS Fiddle with these examples: http://jsfiddle.net/cHRfg/2/

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

+5
source share
2 answers

. ​​: http://jsfiddle.net/timrwood/cHRfg/3/

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

. http://momentjs.com/docs/#/parsing/string-formats/

moment.fn.isValid, , 5-8. 1.7.0. https://github.com/timrwood/moment/pull/306

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

>= 1.7.0 :

parsed.isValid()

< 1.7.0 isValid():

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

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

+1

All Articles