Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js validating invalid date "2013-10-311"

Running moment.js, 2.2.1

moment("2010-10-319", ["YYYY-MM-DD"]).isValid()

... returns true, and the moment object would be set to 31 October 2010. The parser seems to strip extraneous characters of any sort:

moment("2010-10-31a", ["YYYY-MM-DD"]).isValid(); // true

Curiouser, if you add additional format choices, then the "stripping" becomes limited to only one character! (Shouldn't the format strings tests be ORed?)

moment("2010-10-319", ["MM/DD/YYYY", "MM-DD-YYYY", "YYYY-MM-DD"]).isValid(); // true
moment("2010-10-3199", ["MM/DD/YYYY", "MM-DD-YYYY", "YYYY-MM-DD"]).isValid(); // false (!!!)

Is this behaviour by design? I'm not getting why.

EDIT: A commenter found another case where extra characters beyond one are, indeed, stripped:

moment("2010-10-319qr", ["MM/DD/YYYY", "MM-DD-YYYY", "YYYY-MM-DD"]).isValid(); // true (!)

Here is is in action: http://jsfiddle.net/grahampcharles/r42jg/6/ (updated with new case)

like image 583
Graham Charles Avatar asked Sep 25 '13 06:09

Graham Charles


People also ask

How do you check if a date is valid in moment?

isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.

How do you check if a string is a valid date with MomentJS?

Testing for Date Legality If you only want to know whether a date string was successfully converted into a proper date object, you can invoke the isValid() method on the moment instance variable: var aDate = moment(dateElt. value, 'YYYY-MM-DD', true); var isValid = aDate. isValid();

Is MomentJS deprecated?

MomentJs recently announced that the library is now deprecated. This is a big deal for the javascript community who actively downloads moment almost 15 million times a week.


2 Answers

Moment.js version 2.3.0 added strict parsing.

moment("2010-10-319", ["YYYY-MM-DD"]).isValid();       // true
moment("2010-10-319", ["YYYY-MM-DD"], true).isValid(); // false

moment("2010-10-31a", ["YYYY-MM-DD"]).isValid();       // true
moment("2010-10-31a", ["YYYY-MM-DD"], true).isValid(); // false

var formats = ["MM/DD/YYYY", "MM-DD-YYYY", "YYYY-MM-DD"];

moment("2010-10-319",  formats).isValid(); // true
moment("2010-10-3199", formats).isValid(); // false

moment("2010-10-319",  formats, true).isValid(); // false
moment("2010-10-3199", formats, true).isValid(); // false

moment("2010-10-319qr", formats).isValid();       // true
moment("2010-10-319qr", formats, true).isValid(); // false
like image 164
timrwood Avatar answered Nov 02 '22 23:11

timrwood


create an Issue on the Git Repository from momentjs https://github.com/moment/moment/ the best way to handle this error.

like image 21
squadwuschel Avatar answered Nov 03 '22 00:11

squadwuschel