Javascript Date allows invalid data (e.g. Feb 30th)

Viewed 2964

How to validate a date? I mean not the format, but the logic. For example: Feb 30th is not a valid date.

var date = new Date("2015-02-29T13:02:49.073Z"); // 2015 Feb 29th does not exist
console.log(date.toISOString());

Returns 2015-03-01T13:02:49.073Z (March 1st).

But I want a information that this date (input) is not valid.

Edit: Tested in Chrome. Firefox returns "invalid date". But not on parsing. Only when the date is used (e.g. toISOString()) an exception is thrown.

try
{
  var date = new Date("2015-02-29T13:02:49.073Z");
  console.log(date.toISOString());
}
catch(e)
{
    console.log("error: " + e.message);
}

Firefox:

invalid date

Chrome:

(nothing, just switched to the next date.)

Summary: It is browser-dependent. So, not recommended to use.

jsfiddle example

6 Answers
Related