如何使用jQuery验证年龄?

时间:2011-11-15 12:03:06

标签: jquery forms

我需要验证酒精网站的年龄。我需要的就是这里。我快到了,但我不确定是否正确。 在当地不起作用。我需要验证 Cookie 提醒我字段和 DOB

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>

<script>
$(document).ready(function(){
    //AV
    var container = $("#container");
    var avContainer = $("#av-container");
    var mcf = new mcFramework(container, avContainer);
    mcf.mcSetCallbackFunction(function() { document.cookie = "site=" + document.domain.replace(/\./, "") + "av; path=/"; if (window.location.href != 'page2.html') { window.location.href = 'page2.html'; } } 

);


function mcFramework(ContentContainer, AVContainer) {

    //global vars
    var _AVContent = 'You need to be of legal drinking age to continue.';
    var _AVFailContent = 'You must be of legal drinking age (21 or older) to enter our site. You are being redirected to http://www.thecoolspot.gov/ - a place for teens to find info on alcohol and resisting peer pressure.';
    var _ContentContainer = ContentContainer;
    var _AVContainer = AVContainer;
    var _CallbackFunction = "";
    var _SiteCode = "";

    // Set the tracking tag function which will fire on AV or AV Fail
    this.mcSetCallbackFunction = function(val) { _CallbackFunction = val };
    this.mcSetSiteCode = function(val) { _SiteCode = val };


    //add AV form to page
    avhtml = '<div id="Form">'
               + '<div id="mc_avcontent">' + _AVContent + '</div>'
           + '<div id="mc_averrors"></div>'
               + '<p class="inputs">'
               + '<input type="text" id="mc_avday" name="mc_avday" value="DD" maxLength="2" tabindex="1" autocomplete="off" />'
               + '<input type="text" id="mc_avmonth" name="mc_avmonth" value="MM" maxLength="2" tabindex="2" autocomplete="off" />'
               + '<input type="text" id="mc_avyear" name="mc_avyear" value="YYYY" maxLength="4" tabindex="3" autocomplete="off" />'
               + '</p>'
               + '<p class="jqtransform remember">'
               + '<input name="RememberMe" id="RememberMe" type="checkbox" class="jqtransform">'
               + '<label for="RememberMe">Remember Me</label>'
               + '</p>'
               + '<div id="submit" style="cursor:pointer;">submit</div>'
               + '</div>';

    _AVContainer.append(avhtml);

    initForm();


    function _AgeVerify(monthU, dayU, yearU) {

        var min_age = 21;

        /* change "age_form" to whatever your form has for a name="..." */
        var year = parseInt(yearU);
        var month = parseInt(monthU) - 1;
        var day = parseInt(dayU);

        var theirDate = new Date((year + min_age), month, day);
        var today = new Date;

        if ( (today.getTime() - theirDate.getTime()) < 0) {
            _ShowAVFail();
        }
        else {
            _SetAVCookie();
            _ShowContent();
        }

    }

    function _ShowAVFail(callback) 
    {
        avfailhtml = '<div id="mc_avfail">' + _AVFailContent + '</div>';
        $("#mc_avform").html(avfailhtml);

        setTimeout('document.location.href="http://www.thecoolspot.gov"', 5000);

        if (_AVFailTag) {
            _AVFailTag();
        }
    }

    function _ShowContent() 
    {
        _AVContainer.hide();
        _ContentContainer.show();
        _SetAVCookie();
        if (_CallbackFunction) {
            _CallbackFunction();
        }
    }


    function initForm() 
    {
        // Add form event listners
        $("#submit").click(_AVFormSubmit);
        $("#mc_avform").keyup(_AVFormAutoTab);

        $("#mc_avday").keydown(clearField);
        $("#mc_avmonth").keydown(clearField);
        $("#mc_avyear").keydown(clearField);

        // Set focus on month field
        $("#mc_avmonth").focus();
        $("#mc_avmonth").select();
    }

    function clearField() {
        if ($(this).val() == "MM" || $(this).val() == "DD" || $(this).val() == "YYYY") {
            $(this).val("");
        }
    }

    // Handle auto tabbing
    function _AVFormAutoTab(e) 
    {
        var srcElem = (window.event) ? e.srcElement : e.target;
        var day = $("#mc_avday").val();
        var month = $("#mc_avmonth").val();
        var year = $("#mc_avyear").val();     

        if (e.keyCode == 13) {
            _AVFormSubmit();
        } else {
            switch (srcElem.id) {
                case "mc_avday":
                    if (day.match(/^[0-9]{2}$/)) {
                        $("#mc_avyear").focus();
                        $("#mc_avyear").select();
                    }
                    break;
                case "mc_avmonth":
                    if (month.match(/^[0-9]{2}$/)) {
                        $("#mc_avday").focus();
                        $("#mc_avday").select();
                    }
                    break;
                // case "mc_avyear":
                //     if (year.match(/^[0-9]{4}$/)) {
                //         $("#mc_avzip").focus();
                //         $("#mc_avzip").select();
                //     }
                default:
                    result = 'unknown';
            }
        }
    }


    // Submit AV form
    function _AVFormSubmit() 
    {
        if (_AVFormValidate()) {
            var day = $("#mc_avday").val();
            var month = $("#mc_avmonth").val();
            var year = $("#mc_avyear").val();
            _AgeVerify(month, day, year);
        }
    }

    // ======================
    // = AV Form Validation =
    // ======================

    // Validate the AV form
    function _AVFormValidate() {
      var day = $("#mc_avday");
        var month = $("#mc_avmonth");
        var year = $("#mc_avyear");

        error_day = 'Please enter a valid day.';
        error_month = 'Please enter a valid month.';
        error_year = 'Please enter a valid year.';
        error_date = 'Please enter a valid date.';


        var av_errors = $('#mc_averrors');
        if (!(_isNumeric(day.val()))) {
            av_errors.text(error_day);
            day.focus();
            return false;
        }
        if (!(_isNumeric(month.val()))) {
            av_errors.text(error_month);
            month.focus();
            return false;
        }

        if (!(_isNumeric(year.val()))) {
            av_errors.text(error_year);
            year.focus();
            return false;
        }
        if (year.val().length < 4) {
            av_errors.text(error_year);
            year.focus();
            return false;
        }

        if (!_checkdate(month.val(), day.val(), year.val())) {
            av_errors.text(error_date);
            return false;
        }

    }

    // Check if a string is numeric
    function _isNumeric(str) {
        return /^\d+$/.test(str);
    }

    // Check if a string is a valid date
    function _checkdate(m, d, y) {
        var now = new Date(); // current date from clients system
        var yc = now.getYear(); // get current year
        if (yc < 2000) yc = yc + 1900; // in case the year is < 2000
        var yl = yc - 120; // least year to consider
        var ym = yc; // most year to consider

        if (m < 1 || m > 12) return (false);
        if (d < 1 || d > 31) return (false);
        if (y < yl || y > ym) return (false);
        if (m == 4 || m == 6 || m == 9 || m == 11)
            if (d == 31) return (false);
        if (m == 2) {
            var b = parseInt(y / 4);
            if (isNaN(b)) return (false);
            if (d > 29) return (false);
            if (d == 29 && ((y / 4) != parseInt(y / 4))) return (false);
        }
        return (true);
    }

}

//Date helpers

function checkleapyear(datea) {
    if (datea.getYear() % 4 == 0) {
        if (datea.getYear() % 10 != 0) {
            return true;
        }
        else {
            if (datea.getYear() % 400 == 0)
                return true;
            else
                return false;
        }
    }
    return false;
}

function DaysInMonth(Y, M) {
    with (new Date(Y, M, 1, 12)) {
        setDate(0);
        return getDate();
    }
}
function datediff(date1, date2) {
    var y1 = date1.getFullYear(), m1 = date1.getMonth(), d1 = date1.getDate(),
     y2 = date2.getFullYear(), m2 = date2.getMonth(), d2 = date2.getDate();
    if (d1 < d2) {
        m1--;
        d1 += DaysInMonth(y2, m2);
    }
    if (m1 < m2) {
        y1--;
        m1 += 12;
    }
    return [y1 - y2, m1 - m2, d1 - d2];
}

function set_cookie(name, value, exp_d, path, domain, secure) {
    var cookie_string = name + "=" + escape(value);

    if (exp_d) {
        var exp = new Date(); //set new date object
        exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * exp_d));   
    }

    if (path)
        cookie_string += "; path=" + escape(path);

    if (domain)
        cookie_string += "; domain=" + escape(domain);

    if (secure)
        cookie_string += "; secure";

    document.cookie = cookie_string;
}

function SetBypassCookie(site) {
    var siteName = site + 'av';
    //var zip = $("#mc_avzip").val();

    set_cookie("site", siteName, 30, "/");
    //set_cookie("zip", zip, 30, "/");

}
});
</script>
<body>

<div id="av-container" class="content">
</div>



</body>
</html>

8 个答案:

答案 0 :(得分:7)

你问他们怎么样 - &#34;你至少XX岁了吗?&#34;要求出生日期并不安全 - 如果他们想要撒谎,他们无论如何都会输入错误的日期。

答案 1 :(得分:3)

通过JavaScript验证是错误的。如果用户关闭JavaScript怎么办?从法律角度来看,您应该在服务器端执行此操作。如果他们对自己的年龄撒谎,那么法律责任可能就在于他们,但如果你没有证实他们的年龄(因为他们已经关闭了JavaScript)那么你就有错。

答案 2 :(得分:0)

关于年龄验证部分,请尝试以下方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(function() {

            $("#frm-verify-age").submit(function(){
                var age = 18; 
                var mydate = new Date($("#bday").val());
                mydate.setFullYear(mydate.getFullYear());
                var currdate = new Date();
                currdate.setFullYear(currdate.getFullYear() - age);
                if ((currdate - mydate) < 0){
                    alert("Sorry, only persons over the age of " + age + " may enter this site");
                    return false;
                }
                    return true;
            });     


            $("#bday").datepicker({
                buttonText: 'Choose a Date'

            });
            $("#bday").mask("99/99/9999");

        });


    });
</script>
</head>
<body>
<form name="frm-verify-age" id="frm-verify-age">
Birthdate <input style="background-color:#FFFFa0" type="text" id="bday" name="bday" size="12" />
<input name="frm-verify-submit" id="frm-verify-submit" type="submit" value="submit" />

</form>
</body>
</html>

用于Cookie保存: https://github.com/carhartl/jquery-cookie

答案 3 :(得分:0)

使用http://timeago.yarp.com插件。

让他们输入他们的出生日期然后你可以使用

jQuery.timeago("2008-07-17");           //=> "3 years ago"

如果该数字&gt; = 21,则他们的年龄

对于cookie,您可以使用此插件 https://github.com/carhartl/jquery-cookie

$.cookie('the_cookie', 'the_value'); //set cookie
$.cookie('the_cookie'); // read cookie

第二次编辑: 完整的来源 http://jsfiddle.net/bhdry/

答案 4 :(得分:0)

Get difference between 2 dates in javascript?

// parse the users input into a date
    var date1 = new Date("7/11/2010"); //birthday
// get today's date
    var date2 = new Date();
// legal age
    var age = 18;
// get the difference in milliseconds since Epoch
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
// convert it to days
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
// there are 365.242199 days in a year * years, this is the minimum # of days old the person must be.  return true or false if they are old enough.
     return (diffDays > (age * 365.242199))​;

答案 5 :(得分:0)

好吧,因为你将有三个输入字段而不是一个,所以任务只是将掩码应用于三个文本框而不是一个,然后构造timeago方法调用的参数。其余的将保持不变。像这样:

$('input[name="DAY"]').mask("99");
$('input[name="MONTH"]').mask("99");
$('input[name="YEAR"]').mask("9999");
$('.deleteCookie').click(function() {
    $.cookie('age', null);
});
$('.submit').click(function() {
    var enteredDOB = $('input[name="DAY"]').val() + "/" +               
                     $('input[name="MONTH"]').val() + "/" +
                     $('input[name="YEAR"]').val();
    var age = jQuery.timeago(enteredDOB);
    if (age === 'NaN years ago') {
        alert('DOB must be valid');
    } else {
        $.cookie('age', age);
        if (parseInt(age, 10) >= 21) {
            alert('you\'re of age');
        } else {
            alert('you\'re too young');
        }
    }
});

if (null !== $.cookie('age')) {
    alert('saved Cookie ' + $.cookie('age'));
}

关于“记住我”功能,这只是一个在页面加载时读取年龄cookie的问题,如果年龄cookie包含有效值,则重定向到下一页,尽管这可能是一个更好的检查完成服务器端。

答案 6 :(得分:0)

$('.submit').click(function() {应为$('#submit').click(function() {

虽然有些奇怪的代码我不理解并导致错误

$('input[type="checkbox"]:checked').length > 0();

答案 7 :(得分:0)

$('.submit').click(function() {

应该是

$('#submit').click(function() {

$(“。submit”)是指CLASS而$(“#submit”)是指ID。

并且您必须添加一些逻辑来检查是否已选中“记住”复选框,我认为您尝试过,但无法查看是否成功,因为代码从未执行过。我为你添加了逻辑(简单的if语句),在其中,你需要添加cookie创建代码。

if ($('#remember').is(":checked")) {
    $.cookie('age', age, { expires: 365 });
} else {
    $.cookie('age', age);
}

(使用https://github.com/carhartl/jquery-cookie

http://jsfiddle.net/bhdry/45/