Possible Duplicate:
Detecting an “invalid date” Date instance in JavaScript
I was using the following to detect a valid date:
var text = $('#Date').val();
var date = Date.parse(text);
if (isNaN(date)) {
// Invalid date
}
But found that Date.parse thinks the following are valid dates (mm/dd/yyyy)
- 2/30/2011
- 11/31/2011
Any other way to detect invalid dates when the number of days surpasses the total number of
days in the month?
UPDATE: An even larger problem is that the jQuery validation plugin doesn’t detect this as an invalid date either!
SOLUTION:
Based on @Guffa’s comments I have created the following function to validate dates:
function validDate(text) {
var date = Date.parse(text);
if (isNaN(date)) {
return false;
}
var comp = text.split('/');
if (comp.length !== 3) {
return false;
}
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);
return (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d);
}
To check if a date is valid you can parse the components of the date, create a
Dateobject from it, and check if the components in the data is the same as the parsed components. If you create aDateobject 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-drather thand/m/y.Example:
Demo: http://jsfiddle.net/Guffa/UeQAK/