简体   繁体   中英

How to check the age using the in given by a date field in a JavaScript?

I want to validate the birthday using a JavaScript . Birthday is given by a date field . Now I want to check whether the relevant person is older than 18 or not. How can I do it? I have created a function to check the age and now I want to invoke it in an another method and display proper error messages.

Here is my code

function validateDOB(){
    var dob = $("[name ='dob']").val();
    var bdYear, year;
    bdYear = dob.substring(6, 10) - 0;
    year = new Date().getFullYear();

    if ((year - bdYear <= 18) && (year - bdYear >= 60)) {
        return false;
    } else {
        return true;
    }


$("#form").validate({
    rules: {
        dob: {
            required: true,       
        }
    }
});

Since it appears you are using the jQuery validate plugin, you should be able to use jQuery.validator.addMethod to register a new validation rule.

function validateDOB (value) {
  var dob = value;  // Format: '12/11/1998'
  var bdYear, year;
  bdYear = dob.substring(6, 10) - 0;
  year = new Date().getFullYear();

  return 18 <= (year - bdYear);
}

// Register custom rule
jQuery.validator.addMethod("over18", validateDOB, "Must be over 18.");

$("#form").validate({
  rules: {
    dob: {
      required: true,
      over18: true    // Use custom rule
    }
  }
});

With moment.js you can query dates. For example, you can query if date A is before date B, and it returns a boolean. Try something like this:

var yearsAgo = moment().subtract(18, 'years');
moment(dob).isBefore(yearsAgo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM