0

I am writing a date validation function by using JavaScript.

function dateCheck(dateString) {
   try {
      return null != new Date(dateString).toISOString();
   }
   catch (error) {
      return false;
   }
}

This function works fine in Chrome, however, in IE and Firefox, I input an invalid date like "11/32/2015", it will regard it as "12/2/2015". I put an invalid date like "23/1/2015", it will regard it as "11/1/2016". I thought toISOString() function can return null if the input date is invalid, but it seems it doesn't.

user2961484
  • 101
  • 1
  • 6
  • 3
    Wouldn't the blame lie on the Date constructor instead of `toISOString()` itself? You're not passing valid date formats to that constructor, by the way. – Frédéric Hamidi Nov 17 '15 at 18:29
  • What makes you think `toISOString` behaves like this? The `Date` constructor will attempt to parse the date. If it produces a valid date (even if the string was invalid), `toISOString` will stringify it. Otherwise, it will throw an error. Never `null`. – Oriol Nov 17 '15 at 18:35

0 Answers0