I'm working on a Date validation function for a custom render in my web app. When I get a string like "abc", what I do is try to parse it to Date using Date.parse()
and it returns NaN since it's not parseable. The interesting part comes when I get a string containing some numbers separated as a token of the string (i.e. "abc 1"), the parse built-in method returns a timestamp. I don't understand why this happens. Does JS think it is a date format?
I try different strings to be parsed and it's curious:
Date.parse("abc") => NaN
Date.parse("abc1") => NaN
Date.parse("abc123") => NaN
Date.parse("abc 1") => timestamp
Date.parse("abc 123") => timestamp
Date.parse("abc 123456") => timestamp
Date.parse("abc 1234567") => NaN
const isDate = string => !isNaN(Date.parse(string) /* returns timestamp */);
isDate("abc 123"); // returns true
If someone can tell me the reason why this happen and any suggestion on how to fix this issue without using an extra library (i.e. moment) would be great!