0

I need to validate if the age for a alcohol website. And what I need is all here. I'm nearly there but I'm not sure is correct . Locally doesn't work. I need the validation, cookies, remind me field and 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
    If your question is how to verify a legal drinking age, please do not dump your whole codebase here but only the relevant code – Esailija Nov 16 '11 at 15:32
  • 9
    If this age restriction is a legal requirement, it's probably not the best idea to put it in javascript where it can be bypassed easily in any browser. Put it server-side. – Rory McCrossan Nov 16 '11 at 15:34
  • @Rory McCrossan - it asks the user for their birth date. Bypassing this requires simply entering a false date, no matter where the code is located. – Vilx- Nov 16 '11 at 15:44
  • Rory - it can also be bypassed easily by entering a fictitious date of birth :) – Stephen Drew Nov 16 '11 at 15:45
  • 3
    @Vilx very true, however that puts the fault on the user. If the OP maintains the check in javascript he is liable legally by creating a fundamentally flawed age verification system. – Rory McCrossan Nov 16 '11 at 15:46

8 Answers8

7

How about you just ask them - "Are you at least XX years old?" Asking for a birth date isn't more secure - if they'll want to lie, they'll enter a wrong date anyway.

Vilx-
  • 104,512
  • 87
  • 279
  • 422
  • 1
    thanks but is the law like that. for a drinking website I need to follow the design and the law. I now need to fix this. with a DOB and a remember me page. no much more. –  Nov 16 '11 at 15:49
  • 1
    So the law is much harsher on drinking websites than adult websites? interesting – Esailija Nov 16 '11 at 15:51
  • Which law as the required answer will differ in different countries/states etc – mmmmmm Nov 16 '11 at 19:07
3

Validating via JavaScript is fallible. What if the user turns JavaScript off? From a legal point of view, you should probably do this server-side. If they lie about their age, then the legal responsibility probably lies with them, but if you don't validate their age (because they have turned JavaScript off) then you are at fault.

Spycho
  • 7,698
  • 3
  • 34
  • 55
0

As for the Age Validation piece, try this:

<!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>

For the Cookie Saving: https://github.com/carhartl/jquery-cookie

Duke Hall
  • 582
  • 4
  • 12
  • I'll check on the cookie saver. – Duke Hall Nov 15 '11 at 12:40
  • that's absolutely amazing. thank you so much. I now need to ad the remember me checkbox. Could you help me and save my ass again please? –  Nov 15 '11 at 12:48
  • dude, I need 3 input: var mydate = new Date($("#bday").val()); var mydate = new Date($("#month").val()); var mydate = new Date($("#year").val()); could you changed slightly please? –  Nov 15 '11 at 12:54
0

Use http://timeago.yarp.com plugin.

let them type in their date of birth and then you can use

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

if that number >= 21 they are of age

for the cookie you can use this plugin https://github.com/carhartl/jquery-cookie

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

SECOND EDIT: full source http://jsfiddle.net/bhdry/

Adam Merrifield
  • 10,307
  • 4
  • 41
  • 58
  • so you saying I have to replace the whole code? could you give me an quick example please? –  Nov 16 '11 at 15:37
  • Adam, is possible having the remember me button and 3 inputs please? –  Nov 16 '11 at 17:34
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))​;
Community
  • 1
  • 1
DefyGravity
  • 5,681
  • 5
  • 32
  • 47
0

Well, since you are going to have three input fields instead of one, the task is just to apply the mask to three textboxes instead of to one, and then constructing the argument to the timeago method call. The rest would be unchanged. Something like this:

$('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'));
}

With regards to the "remember me" functionality, it is just a question of reading the age cookie upon page load, and redirecting to the next page if the age cookie contains a valid value, although this would probably be a check better done server-side.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • thanks dude, and what about the submit button? to the enter.php? –  Nov 17 '11 at 14:01
  • @user1051883 what about it dude? Don't you already have a `
    ` tag surrounding your fields? If not add it. And then add the following line to the end of the age function: `$('#myform').submit();`
    – Klaus Byskov Pedersen Nov 17 '11 at 14:07
  • Looks like is missing all, is loading strait away the enter page like this. –  Nov 17 '11 at 14:24
  • @user1051883, yeah, you probably only want to submit the form right away if the user is of age. So put the `$('#myform').submit();` after the `alert('you are of age');` line. – Klaus Byskov Pedersen Nov 17 '11 at 14:27
  • and I didn't really get the "remember me checkbox" could you be more specific please? –  Nov 17 '11 at 14:33
0

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

although there is some weird code that I don't understand and causes an error

$('input[type="checkbox"]:checked').length > 0();
Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
0
$('.submit').click(function() {

should be

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

$(".submit") refers to a CLASS and $("#submit") refers to an ID.

and you'll have to add some logic for checking if the remember checkbox is checked, i think you attempted to, but weren't able to see if it was successful because the code never executed. I added the logic for you (simple if statement) and within that, you need to add the cookie creation code.

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

(uses https://github.com/carhartl/jquery-cookie)

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

Cory Danielson
  • 14,314
  • 3
  • 44
  • 51
  • 1
    how do I send the page to another one on submit? –  Nov 17 '11 at 15:53
  • I've updated my fiddle. It attempts to send to a different page, but obviously doesn't work because it's hosted on jsfiddle (http://jsfiddle.net/bhdry/39/) – Cory Danielson Nov 17 '11 at 15:57
  • yes, dude is working fine:-) is that complicated to make the "alert" an id or class in a div? –  Nov 17 '11 at 16:01
  • 1
    so cool mate thank you so much dude..., any idea for the alert message? into a div? –  Nov 17 '11 at 16:09
  • to alert the id or class of a div, you'd do `alert($("_____").attr("id"));` or `alert($("_____").attr("class"));` – Cory Danielson Nov 17 '11 at 16:09
  • no problem, would you please mark my answer as best? it's one of the reasons why we answer your questions. – Cory Danielson Nov 17 '11 at 16:13
  • the message saved Cookie 23 years ago is that normal? –  Nov 17 '11 at 16:14
  • i noticed that, it's because of your "timeago" plugin that you're using. if you do parseInt on that value, it will only save the number. I updated the fiddle, also i removed the expiration date when you don't click "remember". With no expiration date, the cookie is deleted when the browser is closed. (http://jsfiddle.net/bhdry/43/) – Cory Danielson Nov 17 '11 at 16:21
  • and because of that I had to change if you check that the DOB is not a number ("NaN") from "NaN years ago" to just "NaN" (http://jsfiddle.net/bhdry/44/) – Cory Danielson Nov 17 '11 at 16:25
  • would be this ok? at the moment is giving my a "undefined" message alert($('you\'re too young').attr('#error')); –  Nov 17 '11 at 16:27
  • No that won't work because what's inside of $('') needs to be a selector to an HTML element, not a string. It's saying undefined, because it's looking in your html for an HTML tag for `` You can just save your error messages as javascript variables and alert those instead of saving error messages inside of HTML. var tooYoungError = "You're too young"; alert(tooYoungError); – Cory Danielson Nov 17 '11 at 16:30
  • var tooYoungError = "You're too young"; alert(tooYoungError); into the HTML? I need a div in the html, #error within the alert on it –  Nov 17 '11 at 16:40
  • $('') tells jQuery to look inside of your HTML code for certain objects. $(".error") will look for an element with a CLASS of error. $("#error") will look for an element with an ID of error. #("div") will look for all divs. It can return multiple results or just one. http://api.jquery.com/jQuery/ – Cory Danielson Nov 17 '11 at 16:41
  • http://jsfiddle.net/bhdry/45/ something like that? or this http://jsfiddle.net/bhdry/46/ – Cory Danielson Nov 17 '11 at 16:42