You seem to be conflating two things here. Valid date objects and valid dates. These are not the same problem.
The question you linked to answers how to test for validity of date objects (whether a date object is an "invalid date" instance). Invalid date objects are generated when you use invalid parameters when constructing them: new Date('?')
What you want is to test if a date string conforms to a predefined date format. This is an entirely different problem that should not be solved by using only date objects.
Generally speaking, there are a couple of reasons for this; the first is that the browsers will helpfully compute overflow months/days/time to the correct date: new Date(2012,0,290)
=== Oct 06 2012.
Secondly because the parser may be locale dependent (mm/dd vs. dd/mm?). When the date is parsed by the browser my locale may cause it roll it to my timezone/DST thus skewing it and messing up detection (.getDate
may now return next day over). Even worse, this may only occur across some timezones at certain parts of the year.
I strongly encourage using a library like date.js to handle this stuff because dates are much harder than you think! If you absolutely must validate by hand, then I recommend doing it in detail like this:
function isValidDate (str) {
// parse to numbers
const rm = str.split('/');
const m = 1 * rm[0];
const d = 1 * rm[1];
const y = 1 * rm[2];
if (isNaN(m * d * y)) {
return false;
}
// day can't be 0
if (d < 1) {
return false;
}
// month must be 1-12
if (m < 1 || m > 12) {
return false;
}
// february
if (m === 2) {
const isLeapYear = ((y % 4 === 0) && (y % 100 !== 0)) || (y % 400 === 0);
// leap year
if (isLeapYear && d > 29) {
return false;
}
// non-leap year
if (!isLeapYear && d > 28) {
return false;
}
}
// test any other month
else if (
((m === 4 || m === 6 || m === 9 || m === 11) && d > 30) ||
((m === 1 || m === 3 || m === 5 || m === 7 || m === 8 || m === 10 || m === 12) && d > 31)) {
return false;
}
return true;
}
As a jsFiddle: http://jsfiddle.net/3pMPp/1/
As a jsPerf: http://jsperf.com/silly-date-valiation
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…