JavaScript Detecting Valid Dates

To check if a date is valid you can parse the components of the date, create a Date object from it, and check if the components in the data is the same as the parsed components. If you create a Date object from compnents that are out of range, the values will flow over to the next/previous period to create a valid date.

For example, new Date(2011,0,42) will create an object that contains the date 2/11/2011 instead of 1/42/2011.

By parsing the components instead of the full date you will also get around the problem with different date formats. My browser will for example expect a date format like y-m-d rather than d/m/y.

Example:

var text="2/30/2011";
var comp = text.split("https://stackoverflow.com/");
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date = new Date(y,m-1,d);
if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
  alert('Valid date');
} else {
  alert('Invalid date');
}

Demo: http://jsfiddle.net/Guffa/UeQAK/

Leave a Comment