18

I am trying to validate a date input, so if it is correct, I handle one way, and if invalid, I handle another...

var date, datestring, e;

datestring = "2012-03-222";

try {
  date = new Date(datestring);
  /* Ends up logging `Invalid Date`
  */

  console.log(date);
} catch (_error) {
  e = _error;
  /* Should come here and log `Error: Invalid Date` or the likes
  */

  console.log("Erorr: " + e);
}

I could just check the returned string, and see if it is Invalid Date or not, but am both surprised that try/catch does not work for this scenario, and concerned that there might be other error messages I do not match.

How should I handle this problem?

Billy Moon
  • 57,113
  • 24
  • 136
  • 237

1 Answers1

17

Date objects do not throw an error if they are invalid. There is a method described in this related question that will determine if a date is valid.

Community
  • 1
  • 1
Michael Pratt
  • 3,438
  • 1
  • 17
  • 31