更好的验证(请参阅working example)。如果你要问生日,为什么不检查它们是否也是可信的?第一部分检查无效日期(超出范围,包括该月特定范围之外的日期);第二部分将那些还未出生的人,或者太老的人看作是合理的。
/**
* 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;
}
你不需要jQuery来执行良好的ol时尚的javascript验证。读取字符串值并将其解析为整数。检查它是否在预期的值范围内。如果没有什么不合适的地方,它是有效的。 – Neil
您是否验证用户输入了“01”而不仅仅是“1” - 如果是这样,您最好填充该值。如果您需要验证“01”或“1”是否有效,@Neil解析该值是正确的。 'var monthValue = parseInt(month,10);' – Fenton
你需要检查它是一个实际的日期,还是只是数字在范围内?例如,2012年2月29日生效,2013年2月29日生效? – andi