Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can i parse invalid date string? [duplicate]

I use a function that check if entered value is a valid text for specific purpose in my application.

valid value is a string where it's not valid date or number neither true or false.

checkText(str) {
    return isNaN(str) && isNaN(Date.parse(str)) && ['true', 'false'].indexOf(str) == -1;
} 

It works properly, but i faced an issue with this string: "New Item 3".

Date.parse("New Item 3") returns a number, but why!!? also, if you changed 3 into any number less than 13 it will return number!

Anyone here can explain to me what happens?

like image 331
Nimer Esam Avatar asked Dec 23 '22 20:12

Nimer Esam


2 Answers

Lesson learned: Date.parse is not a date validator.

Even MDN says:

It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).

And further down

The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return NaN.

However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided

like image 70
Federico klez Culloca Avatar answered Dec 27 '22 11:12

Federico klez Culloca


In fact the problem here is coming from Date.parse() method, if you check:

Date.parse("New Item 3");

It will return:

983401200000

console.log(Date.parse("New Item 3"));

So the fact here is that Date.parse() will behave according the browser specifications and may or not return a Number. It depends on the browser.

And you can see from the Date.parse() MDN reference that:

The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return NaN.

However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided.

like image 24
cнŝdk Avatar answered Dec 27 '22 11:12

cнŝdk