9

I have a div in jsp as follows:

 <input type="text" id="year" placeholder=" Year"  class="year"  name= "year" value=""/>

I want to calculate the difference between current year and entered year. I have to show the error if the value does not lie within some range. This is my custome jquery validator function.

jQuery.validator.addMethod('validAge', function (value, element, params) {
    alert("inside add method");
    var currentYear = (new Date).getFullYear();
    var range = currentYear - $element.val();;
    if(range >10 && range< 70) 
        {
        return  true;
        }
    return false;
}),

But it is showing error at element.val I have defined the rule as

 $('#signup_form').validate({ // initialize the plugin

    rules: {
        year: {
            validage: true,
           },
    },
    messages: {
        year: "Invalid year",
   },
   },
  });
1
  • 1
    validage != validAge Commented Mar 27, 2015 at 10:11

2 Answers 2

10

In jquery addMethod element (the element to be validated) and value (the current value of the validated element)

 jQuery.validator.addMethod("validAge", function (value, element, params) {
        alert("inside add method");
        var currentYear = (new Date).getFullYear();
        var range = currentYear - value;

       return this.optional(element) || (range >10 && range< 70) 

    },'Enter range in between 10 to 70');

Remove commas where not needed and also see case sensitiveness.

var validator = $('#form').validate({
    rules: {
        year: {
            validAge: true
        }
    },
    messages: {
        year: "Invalid year"
    }
});
Sign up to request clarification or add additional context in comments.

Comments

3

Method name is not properly spelled, check 'validage' instead of 'validAge'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.