代码之家  ›  专栏  ›  技术社区  ›  user244394

javascript月、日、年检查

  •  0
  • user244394  · 技术社区  · 14 年前

    我正在检查年/月/日。

    当前,当您输入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;
    });
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Gabriele Petrioli    7 年前

    您应该使用以下方法来验证输入是否确实是数字,然后检查范围

    复制自 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*/}
    }