Validate date for anyone over 18 with jQuery

前端 未结 6 2090
借酒劲吻你
借酒劲吻你 2021-01-18 03:07

I have a form on my site that should validate for anyone who is over 18.

var day = $(\"#dobDay\").val();
var month = $(\"#dobMonth\").val();
var year = $(\"         


        
6条回答
  •  逝去的感伤
    2021-01-18 03:48

    18 year old validation rule for jQuery Validator plugin using addMethod function.

    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"
        );
    

    and

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

提交回复
热议问题