使用jQueryvalidation18岁以上的任何人的日期

我的网站上有一个表格,可以validation18岁以上的人。

var day = $("#dobDay").val(); var month = $("#dobMonth").val(); var year = $("#dobYear").val(); var age = 18; var mydate = new Date(); mydate.setFullYear(year, month-1, day); var currdate = new Date(); currdate.setFullYear(currdate.getFullYear() - age); var output = currdate - mydate if ((currdate - mydate) > 0){ // you are not 18 } 

但它完全相反的方式。 我想if语句在用户未满18岁时采取行动。

提前谢谢你的帮助

检查这个DEMO

 var day = 12; var month = 12; var year = 2006; var age = 18; var setDate = new Date(year + age, month - 1, day); var currdate = new Date(); if (currdate >= setDate) { // you are above 18 alert("above 18"); } else { alert("below 18"); } 
 var day = $("#dobDay").val(); var month = $("#dobMonth").val(); var year = $("#dobYear").val(); var age = 18; var mydate = new Date(); mydate.setFullYear(year, month-1, day); var currdate = new Date(); currdate.setFullYear(currdate.getFullYear() - age); if(currdate < mydate) { alert('You must be at least 18 years of age.'); } 

这是我测试的更轻的版本:

 var day = 1; var month = 1; var year = 1999; var age = 18; var cutOffDate = new Date(year + age, month, day); if (cutOffDate > Date.now()) { $('output').val("Get Outta Here!"); } else { $('output').val("Works for me!"); } 

关键是要将最小年龄添加到生日,并确认它是在当前日期之前。 您正在检查当前日期是否减去最小年龄(基本上是允许的最新生日)是否大于提供的生日,这将反过来给您。

使用addMethod函数的jQuery Validator插件的18年validation规则。

 jQuery.validator.addMethod( "validDOB", function(value, element) { var from = value.split(" "); // DD MM YYYY // var from = value.split("/"); // DD/MM/YYYY var day = from[0]; var month = from[1]; var year = from[2]; var age = 18; var mydate = new Date(); mydate.setFullYear(year, month-1, day); var currdate = new Date(); var setDate = new Date(); setDate.setFullYear(mydate.getFullYear() + age, month-1, day); if ((currdate - setDate) > 0){ return true; }else{ return false; } }, "Sorry, you must be 18 years of age to apply" ); 

 $('#myForm') .validate({ rules : { myDOB : { validDOB : true } } }); 

如果它正在以相反的方式工作你是否尝试交换>在第二行到最后一行的<

我认为如果我们重命名变量会更容易理解

mydate => givenDate
currdate => thresholdDate

如果givenDate> thresholdDate =>你不是18岁
别= =你是18岁

 if ( givenDate > thresholdDate ){ // you are not 18 } 

 if ((givenDate - thresholdDate) > 0){ // you are not 18 } 

 if ((mydate - currdate ) > 0){ // you are not 18 }