jQuery 验证器 addMethod 无法正常工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14605776/
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
jQuery validator addMethod not working correctly
提问by Chris
I am using a new validation rule with the jQuery validation. It is somehow not applied though? It is contained within a javascript file that is included after jquery.validate.js
. When should I include the js file that contains my custom rules for them to be applied?
我在 jQuery 验证中使用了新的验证规则。它不知何故不适用?它包含在 .js 之后的 javascript 文件中jquery.validate.js
。我应该什么时候包含包含我要应用的自定义规则的 js 文件?
When I enter 0.1
into an input that should validate against this nothing happens, the console.log
isnt hit neither is the alert.
当我输入0.1
应该对此进行验证的输入时,没有任何反应,console.log
警报也没有命中。
$(document).ready(function(){
jQuery.validator.addMethod('integer', function(value, element, param) {
console.log(value); alert("hey");
return (value != 0) && (value == parseInt(value, 10));
}, 'Please enter a non zero integer value!');
});
HTML
HTML
<input class="required number integer valid" type="text" data-type="int" value="1" name="Default.MinArrivals" title="">
The classes required
and number
work perfectly, it is just my integer
method that doesn't work correctly.
类required
和number
工作完美,只是我的integer
方法不能正常工作。
回答by Sparky
It seems to be working for me:
它似乎对我有用:
Please show the rest of your code.
请显示您的其余代码。
jQuery:
jQuery:
$(document).ready(function () {
jQuery.validator.addMethod('integer', function (value, element, param) {
return (value != 0) && (value == parseInt(value, 10));
}, 'Please enter a non zero integer value!');
$('#myform').validate({
rules: {
field1: {
required: true,
integer: true
}
}
});
});
HTML:
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="submit" />
</form>
Quote: When should I include the js file that contains my custom rules for them to be applied?
Quote: 我应该什么时候包含包含我要应用的自定义规则的 js 文件?
As long as:
只要:
1) your code (or file) comes afteryou've properly included jQuery
and jQuery Validate plugin
(in that order).
1)您的代码(或文件)在您正确包含jQuery
和jQuery Validate plugin
(按该顺序)之后出现。
AND
和
2) your code is all contained within a document.ready
function.
2)您的代码都包含在一个document.ready
函数中。
Notes: The ordering of .validator.addMethod
and .validate()
do not matter with respect to each other as long as you follow 1 & 2. http://jsfiddle.net/jp93D/
注:的顺序.validator.addMethod
和.validate()
只要你按照1&2,不事相对于彼此 http://jsfiddle.net/jp93D/
回答by stuartdotnet
I had this problem once because I was using the html id rather than the name in the rules.
我曾经遇到过这个问题,因为我在规则中使用了 html id 而不是名称。
Might help someone.
可能会帮助某人。