Desmond Desmond - 3 months ago 13
jQuery Question

Age check by birthdate to exact date, for jquery.validate

I am using this script to verify if someone is over 16 when they enter a birthdate. The problem is, it only validates with current year accuracy, so if someone is turning 16 this year but still 15, it would still pass.

Can anyone tell me how I can validate to the day, the Date() javascript function doesn't have enough info online.

My code:

$.validator.addMethod("check_date_of_birth", function(value, element) {

var dateOfBirth = $("#dob").val();
var arr_dateText = dateOfBirth.split("/");
day = arr_dateText[0];
month = arr_dateText[1];
year = arr_dateText[2];

var mydate = new Date();
mydate.setFullYear(year, month-1, day);

var currdate = new Date();

var totalage = (currdate.getFullYear()) - (mydate.getFullYear());

if (totalage < 16){
$.validator.messages.check_date_of_birth = "Sorry, only persons over the age of 16 can be covered";
return false;
}
return true;
});

Answer

You can check whether the entered date > current date - 16 years like

$.validator.addMethod("check_date_of_birth", function (value, element) {
    if (this.optional(element)) {
        return true;
    }

    var dateOfBirth = value;
    var arr_dateText = dateOfBirth.split("/");
    day = arr_dateText[0];
    month = arr_dateText[1];
    year = arr_dateText[2];

    var mydate = new Date();
    mydate.setFullYear(year, month - 1, day);

    var maxDate = new Date();
    maxDate.setYear(maxDate.getYear() - 16);

    if (maxDate < mydate) {
        return false;
    }
    return true;
}, 'Sorry, only persons over the age of 16 can be covered');

Demo: Fiddle