0

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,       
        }
    }
});
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Mike
  • 1,017
  • 4
  • 19
  • 34

2 Answers2

1

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
    }
  }
});
thgaskell
  • 12,772
  • 5
  • 32
  • 38
  • I took out the under 60 validation for simplicity and since the question seemed to just want to check if the date string was **older than 18**. – thgaskell Dec 11 '16 at 22:04
0

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);
416E64726577
  • 2,214
  • 2
  • 23
  • 47
Owen J Lamb
  • 254
  • 1
  • 10