Age Check and jquery

2019-08-28 12:29发布

问题:

Does anyone have any solid examples of how to implement a jQuery or javascript based age checker? I'm looking to send someone to a page where they need to enter in the Day, Month and Year at least once a day when they hit any page on the site. Once they validate as 18 then they would not be pestered again until the next day if they return.

Any ideas?

回答1:

A cookie-based solution does seem a logical fit since you can programmatically modify them from JavaScript and you can set their expiry. Calculating the date in pure JavaScript can be done as such:

var millisPerYear = 1000 * 60 * 60 * 24 * 365;
var birthdate = new Date(year, month, day); // from user input.
var age = ((new Date().getTime()) - birthdate.getTime()) / millisPerYear;
// Now set the "age" cookie.

All that is left is for your server-side response handlers to return content conditionally based on the value of the "age" cookie from the request agent.



回答2:

There seem to be a number of existing resources on the web for implementing similar functionality. All of them create a cookie with the birth day selector which held by the user and can be set to expire a day later. Obviously this can be a problem if your users don't have cookies enabled. Below are a couple of examples.

http://www.webdesignforums.net/php-67/age_verification_script-30188/index2.html

http://www.techerator.com/2010/09/how-to-perform-age-verification-with-jquery-and-cookies-mmm-cookies/



回答3:

There is a wonderful Date library for JavaScript called DateJS. It makes date operations extremely simple.

Your first step is, of course, to parse the date that is provided. DateJS provides a lot of parsing functionalities, such as:

Date.parse("Mar 3 2010");
Date.parse('March 20th 1973');
Date.parse("03 12 2010");

Once you have parsed the date, you can compare it to the date 18 years ago. This is also easy with DateJS

var userBDay = Date.parse("Mar 3 1970");
var eighteenYearsAgo = (18).years().ago();
var is18 = (userBDay >= eighteenYearsAgo);

You are of course assuming the user is honest. Not to mention JS can be disabled, or modified client side. But that is an entirely different discussion.

EDIT: Had forgotten about your mention of only doing verification once a day. This would require either:

  • Cookie (client side)
  • HTML5 LocalStorage (client side)
  • Session, where last verification can be provided either at the time of the page rendering or through an AJAX request. (server side w/ client side component)