如何使用jQuery验证年龄? [英] How do I verify age using jQuery?
问题描述
我需要验证酒精网站的年龄。我需要的是这里。我快到了,但我不确定是否正确。
本地不起作用。我需要验证, Cookie ,提醒我字段和 DOB
< html xmlns =http://www.w3.org/1999/xhtml>
< head>
< / head>
< script type =text / javascriptsrc =http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js><<< ; /脚本>
< 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-容器);
var mcf = new mcFramework(container,avContainer);
mcf.mcSetCallbackFunction(function(){document.cookie =site =+ document.domain.replace(/ \。 /(window.location.href!='page2.html'){window.location.href ='page2.html';}}
$;
函数mcFramework(ContentContainer,AVContainer){
//全局变量
var _AVContent ='您需要合法;
var _AVFailContent ='您必须是合法饮酒年龄(21岁或以上)才能进入我们的网站,您将被重定向到http://www.thecoolspot.gov/ - 一个地点';
var _ContentContainer = ContentContainer;
var _AVContainer = AVContainer;
var _CallbackFunction =;
var _Site Code =;
//设置将在AV或AV上触发的跟踪标签功能失败
this.mcSetCallbackFunction = function(val){_CallbackFunction = val};
this.mcSetSiteCode = function(val){_SiteCode = val};
//将AV表单添加到页面
avhtml ='< div id =Form>'
+'< div id =mc_avcontent >'+ _AVContent +'< / div>'
+'< div id =mc_averrors>< / div>'
+'< p class =inputs >'
+'< input type =textid =mc_avdayname =mc_avdayvalue =DDmaxLength =2tabindex =1autocomplete =off/> '
+'< input type =textid =mc_avmonthname =mc_avmonthvalue =MMmaxLength =2tabindex =2autocomplete =off/>'
+'< input type =textid =mc_avyearname =mc_avyearvalue =YYYYmaxLength =4tabindex =3autocomplete =off/>'
+'< / p>'
+'< p class =jqtransform remember>'
+'< input name =RememberMeid =RememberMetype =checkbox class =jqtransform>'
+'< label for =Rememb erMe>记住我< / label>'
+'< / p>'
+'< div id =submitstyle =cursor:pointer; div>'
+'< / div>';
_AVContainer.append(avhtml);
initForm();
函数_AgeVerify(monthU,dayU,yearU){
var min_age = 21;
/ *将age_form更改为任何形式的名称=...* /
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; ((today.getTime() - theirDate.getTime())< 0){
_ShowAVFail();
if
}
else {
_SetAVCookie();
_ShowContent();
}
}
函数_ShowAVFail(回调)
{
avfailhtml ='< div id =mc_avfail>' + _AVFailContent +'< / div>';
$(#mc_avform)。html(avfailhtml);
setTimeout('document.location.href =http://www.thecoolspot.gov',5000);
if(_AVFailTag){
_AVFailTag();
函数_ShowContent()
{
_AVContainer.hide();
_ContentContainer.show();
_SetAVCookie();
if(_CallbackFunction){
_CallbackFunction();
$ b函数initForm()
{
//添加表单事件列表
$(#submit )。单击(_AVFormSubmit);
$(#mc_avform)。keyup(_AVFormAutoTab);
$(#mc_avday)。keydown(clearField);
$(#mc_avmonth)。keydown(clearField);
$(#mc_avyear)。keydown(clearField);
//将焦点设置在月份字段
$(#mc_avmonth)。focus();
$(#mc_avmonth)。select();
函数clearField(){
if($(this).val()==MM|| $(this).val()== DD|| $(this).val()==YYYY){
$(this).val();
//处理自动标签
函数_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){
casemc_avday:
if(day.match(/ ^ [0-9] {2} $ /) ){
$(#mc_avyear)。focus();
$(#mc_avyear)。select();
}
break;
casemc_avmonth:
if(month.match(/ ^ [0-9] {2} $ /)){
$(#mc_avday)。focus();
$(#mc_avday)。select();
}
break;
// casemc_avyear:
// if(year.match(/ ^ [0-9] {4} $ /)){
// $(#mc_avzip )。焦点();
// $(#mc_avzip)。select();
//}
默认值:
result ='unknown';
$ b $ //提交AV格式
函数_AVFormSubmit()
{
if (_AVFormValidate()){
var day = $(#mc_avday)。val();
var month = $(#mc_avmonth)。val();
var year = $(#mc_avyear)。val();
_AgeVerify(月,日,年);
}
}
// ======================
// = AV表单验证=
// ======================
//验证AV表单
函数_AVFormValidate(){
var day = $(#mc_avday);
var month = $(#mc_avmonth);
var year = $(#mc_avyear);
error_day ='请输入有效日期。';
error_month ='请输入一个有效的月份。';
error_year ='请输入一个有效的年份。';
error_date ='请输入有效的日期。';
var av_errors = $('#mc_averrors');
if(!(_ isNumeric(day.val()))){
av_errors.text(error_day);
day.focus();
返回false; $(b)b
if(!(_ isNumeric(month.val()))){
av_errors.text(error_month);
month.focus();
返回false; (!(_是数字(year.val()))){
av_errors.text(error_year);
}
if
year.focus();
返回false; (year.val()。length< 4){
av_errors.text(error_year);
}
if
year.focus();
返回false; $!
$ b if(!_checkdate(month.val(),day.val(),year.val())){
av_errors.text(error_date);
返回false;
}
}
//检查字符串是否为数字
函数_isNumeric(str){
return / ^ \d + 。$ /测试(STR);
}
//检查一个字符串是否为有效日期
函数_checkdate(m,d,y){
var now = new Date(); //来自客户系统的当前日期
var yc = now.getYear(); //获得当前年份
if(yc <2000)yc = yc + 1900; //如果年份是< 2000
var yl = yc - 120; //最少一年考虑
var ym = yc; //大多数年份考虑
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);
}
}
//日期助手
函数checkleapyear(datea){
if(datea.getYear )%4 == 0){
if(datea.getYear()%10!= 0){
return true;
}
else {
if(datea.getYear()%400 == 0)
return true;
else
返回false;
}
}
返回false;
函数DaysInMonth(Y,M){
with(new Date(Y,M,1,12)){
setDate(0);
return getDate();
$ b函数datediff(date1,date2){
var y1 = date1.getFullYear(),m1 = date1.getMonth(),d1 = date1.getDate() ,
y2 = date2.getFullYear(),m2 = date2.getMonth(),d2 = date2.getDate();
if(d1 m1--;
d1 + = DaysInMonth(y2,m2);
}
if(m1 y1--;
m1 + = 12;
}
return [y1 - y2,m1 - m2,d1 - d2];
函数set_cookie(name,value,exp_d,path,domain,secure){
var cookie_string = name +=+ escape(value);
if(exp_d){
var exp = new Date(); //设置新的日期对象
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;
}
函数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-containerclass =content>
< / div>
< / body>
< / html>
$( '.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 )
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>
$('.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)
这篇关于如何使用jQuery验证年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!