最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery validation addMethod not working - Stack Overflow

programmeradmin4浏览0评论

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",
   },
   },
  });

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",
   },
   },
  });
Share Improve this question asked Mar 27, 2015 at 10:10 user3681970user3681970 1,2815 gold badges21 silver badges39 bronze badges 1
  • 1 validage != validAge – Arun P Johny Commented Mar 27, 2015 at 10:11
Add a ment  | 

2 Answers 2

Reset to default 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 mas where not needed and also see case sensitiveness.

var validator = $('#form').validate({
    rules: {
        year: {
            validAge: true
        }
    },
    messages: {
        year: "Invalid year"
    }
});

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

发布评论

评论列表(0)

  1. 暂无评论