更好的验证(参见工作示例)。如果您要问生日,为什么不检查它们是否也合情合理?第一部分检查无效日期(超出范围,包括该月特定范围之外的日期);第二部分排除了尚未出生的人,或者太老而无法成立的人。
/**
* input is year/month/day (month from 1 to 12, day from 1 to 31)
* output is boolean: true if correct and in-range, false if not
*/
function isValidBirthdate(year, month, day, minAge, maxAge) {
// javascript days expect zero-based days and months
month --; day --;
var saysWasBorn = new Date(year, month, day);
if (saysWasBorn.getDate() != day
|| saysWasBorn.getMonth() != month
|| saysWasBorn.getFullYear() != year) {
console.log("impossible date: ");
return false;
}
var now = new Date();
var yearsOld = now.getFullYear() - saysWasBorn.getFullYear();
if ((now.getMonth()*40 + now.getDate() - 1) <
(saysWasBorn.getMonth()*40 + saysWasBorn.getDate())) {
yearsOld --;
}
if (yearsOld > maxAge) {
console.log("too old");
return false;
} else if (yearsOld < minAge) {
console.log("too young");
return false;
}
return true;
}