我的网站上有一张表格可以验证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);
var output = currdate - mydate
if ((currdate - mydate) > 0){
// you are not 18
}
但它完全相反。我想if语句在用户未满18岁时采取行动。
提前感谢您的帮助
答案 0 :(得分:10)
检查此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");
}
答案 1 :(得分:4)
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.');
}
答案 2 :(得分:3)
这是一个稍微轻松的版本tested:
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!");
}
关键是要将最小年龄添加到生日,并确认它是在当前日期之前。您正在检查当前日期是否减去最小年龄(基本上是允许的最新生日)是否大于提供的生日,这将反过来。
答案 3 :(得分:2)
使用addMethod函数的jQuery Validator插件的18年验证规则。
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
}
}
});
答案 4 :(得分:0)
如果它以相反的方式工作,您是否尝试在第二行到最后一行交换>
<
?
答案 5 :(得分:0)
我认为如果我们重命名变量
会更容易理解 mydate =&gt; givenDate
currdate =&gt; thresholdDate
如果givenDate&gt; thresholdDate =&gt;你不是18岁 else =&gt;你才18岁
即
if ( givenDate > thresholdDate ){
// you are not 18
}
即
if ((givenDate - thresholdDate) > 0){
// you are not 18
}
即
if ((mydate - currdate ) > 0){
// you are not 18
}