javascript jquery 验证 addMethod 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29298100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:20:42  来源:igfitidea点击:

jquery validation addMethod not working

javascriptjqueryjquery-validate

提问by user3681970

I have a div in jsp as follows:

我在jsp中有一个div如下:

 <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 验证器功能。

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

但它在 element.val 显示错误我已将规则定义为

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

    rules: {
        year: {
            validage: true,
           },
    },
    messages: {
        year: "Invalid year",
   },
   },
  });

回答by Kamini

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

jquery中的addMethod元素(要验证的元素)和value(被验证元素的当前值)

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

回答by Viswanath D

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

方法名称拼写不正确,请检查“validage”而不是“validAge”