GPX
GPX

Reputation: 3645

Using jQuery validate rule twice for a field

I'm trying to validate an input field that holds a user's date of birth, and I need to do two checks - 1. Make sure the user is 18 years old and 2. Make sure his/her age isn't over 100.

My custom validate method -

$.validator.addMethod(
       "datediff",
       function(value, element, diff_years) {
          var curr_date = new Date().getFullYear();
          var element_date = Date.parse($(element).val()).getFullYear();
          return element_date >= curr_date - diff_years;
       }
);

And here's how I add the rule.

var validator = $('form').validate({
     rules: {
        'dob': {datediff: 18}
     },
     messages: {
         dob: {datediff: 'You have to be 18 or more!'}
     }
});

How do I reuse the datediff rule twice, so that I can do both the checks? I tried just appending another datediff rule, but that didn't work.

Edit: I also need to show 2 distinct messages - for example - 1. "You have to be 18 or more" for the first condition, and "You cannot be more than 100" for the second.

Upvotes: 1

Views: 1787

Answers (3)

Sparky
Sparky

Reputation: 98718

If you need two unique messages, then you'll need two unique rules/methods. You can put your common code into a single function and call it from within the custom method.

Something like this...

function datediff(value, diff_years) {
    var curr_date = new Date().getFullYear();
    var element_date = Date.parse(value.getFullYear();
    return element_date >= curr_date - diff_years;
}

$.validator.addMethod( "over18", function(value, element) {
    // your custom function below
    // var result = datediff(value, 18);
    // return true if age is greater than 18
    // return false and error message will display
}, "You must be over 18");

$.validator.addMethod( "under100", function(value, element) {
    // your custom function below
    // var result = datediff(value, 100);
    // return true if age is less than 100
    // return false and error message will display
}, "You must be under 100");

$('form').validate({
     rules: {
         dob: {
             over18: true,
             under100: true
         }
     }
});

Upvotes: 3

Praveen
Praveen

Reputation: 56501

If you want to handle 2 different messages, then probably you can use max and min

max: Makes the element require a given maximum.
min: Makes the element require a given minimum.

Rules:

    rules: {
        dob: {
            min: 18,
            max: 100,
            required: true
        }
    }

Messages displayed:

    messages: {
        dob: {
            required: "Please enter the age",
            min: "Enter the age above 18",
            max: "Age should be below 100"
        }
    }

Check out in JSFiddle

Upvotes: 1

Yeronimo
Yeronimo

Reputation: 1749

Try using the Range rule:

rules: {
field: {
  required: true,
    range: [18, 100]
  }
}

Source: http://jqueryvalidation.org/range-method

Upvotes: 0

Related Questions