使用 jQuery 验证 18 岁以上任何人的日期

Validate date for anyone over 18 with jQuery

本文关键字:任何人 日期 岁以上 jQuery 验证 使用      更新时间:2023-09-26

我的网站上有一个表单,应该为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 岁时采取行动。

提前感谢您的帮助

检查这个演示

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年验证规则。

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
当前日期 => 阈值日期

如果给定日期>阈值日期 =>则您不是 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
}