2010-10-06 117 views
0

我正在检查MM/DD/YYYY。javascript月份和日期和年份检查

当您输入0/0/0或00/00/0000时,我的脚本将失败。我正在尝试检查用户是否已超过21岁,并且必须输入有效的两位数月份,两位数日期和四位数字年份。

有什么建议吗?

$("#gate-box").submit(function() { 

    var day = $("#day").val(); 
    var month = $("#month").val(); 
    var year = $("#year").val(); 

    var age = 21; 

    var mydate = new Date(); 
    mydate.setFullYear(year, month - 1, day); 

    var currdate = new Date(); 
    currdate.setFullYear(currdate.getFullYear() - age); 
    if ((currdate - mydate) < 0) {   
     $.msg("Sorry, you must be at least " + age + " to enter."); 
     return false; 
    } 
    else if (month > 12) { 
     $('#month').css({ 'border': '1px solid red' }); 
     $.msg("Please enter a valid month."); 
     $('#month').focus(); 
     return false; 
    } 
    else if (day > 31) { 
     $('#month').css({ 'border': 'none' }); 
     $('#day').css({ 'border': '1px solid red' }); 
     $.msg("Please enter a valid day."); 
     $('#day').focus(); 
     return false; 
    } 
    else if (month.length === 0 || day.length === 0 || year.length === 0) { 
     $('#day').css({ 'border': 'none' }); 
     $.msg("Please enter all fields."); 
     return false; 
    } 

    if ((currdate - mydate) > 0) { 
     $.colorbox.close() 
     $.setCookie('diageoagecheck', 'verified', { duration: 3 }); 
    } 
    return false; 
}); 
+0

尝试验证**之前的输入**使用它们来创建日期对象。 – 2010-10-06 20:15:48

+0

如何检查两位数月份,两位数日期和四位数年份。当您输入0/0/0或00/00/0000时,脚本目前失败。 – user244394 2010-10-06 20:26:33

+0

检查它们是否落入(1-31),(1-12),(1900-2100) – 2010-10-06 20:37:21

回答

4

你应该使用下面的方法来验证,如果输入的是确实的数字,然后检查

Validate numbers in JavaScript - IsNumeric()

function IsNumeric(input) 
{ 
    return (input - 0) == input && input.length > 0; 
} 

复制的范围和阅读后使用它像这样(输入

if (!IsNumeric(day) || day < 1) 
    {/*handle wrong day here and return false*/} 
if (!IsNumeric(month) || (month < 1) || (month > 12)) 
    {/*handle wrong month here and return false*/} 
if (!IsNumeric(year) || (year < 1900) || (year > 2100)) 
    {/*handle wrong year here and return false*/} 

var lastDayOfMonth = new Date(year, parseInt(month) + 1, -1).getDate(); 
if (day > lastDayOfMonth) { 
    {/*handle wrong year here and return false*/} 
} 
+0

的可接受范围内。这不会使用正确的日历并检查一个月中的日期。 – 2017-06-10 23:53:16

+0

@TimothyGonzalez OP特别要求自己验证每个字段。 – 2017-06-10 23:59:09

+1

也许OP是错误地问错了问题。如果你正在处理日期,你不能逃避这些字段是相关的。它没有回答这个问题的意图,即确定年龄。如果我出生于2017年4月31日(2017年4月31日不存在的日期),我多大了? – 2017-06-11 00:04:48