Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery validation addMethod not working

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",
   },
   },
  });
like image 966
user3681970 Avatar asked Mar 27 '15 10:03

user3681970


1 Answers

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"
    }
});
like image 188
Kamini Avatar answered Sep 20 '22 16:09

Kamini