javascript 强制 jQuery 验证器验证单个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29542425/
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
Forcing jQuery validator to validate a single element
提问by user1032531
On an edit page, I am using http://jqueryvalidation.org/to validate a form.
在编辑页面上,我使用http://jqueryvalidation.org/来验证表单。
//validate object set using external file linked to page
var myValidateObj = {
"rules": {
"foo": {"required": true,"maxlength": 45,"minlength": 2},
"bar": {"maxlength": 45},
},
"messages": {
"foo": {"required": "Foo is required.",},
"bar": {"maxlength": "bla bla."},
}
};
var validator=$("#myform").validate({
rules: myValidateObj.rules,
messages: myValidateObj.messages,
});
<form id="myForm">
Foo: <input type="text" name="foo" />
Bar: <input type="text" name="bar" />
<input type="submit" value="SAVE">
</form>
On another page, I am displaying the values of the previously described edit page, and allowing inline editing using http://vitalets.github.io/x-editable/. The validation rules and messages still apply, but now are only needed to validate a single field. Assuming the myValidateObj
object exists on this page, can it be used to validate a single field? For instance, within the editable validate callback, how can myValidateObj
be used to validate foo
and return the appropriate message upon not passing validation?
在另一个页面上,我正在显示前面描述的编辑页面的值,并允许使用http://vitalets.github.io/x-editable/进行内联编辑。验证规则和消息仍然适用,但现在只需要验证单个字段。假设myValidateObj
此页面上存在该对象,是否可以使用它来验证单个字段?例如,在可编辑的验证回调中,如何在未通过验证时myValidateObj
验证foo
并返回适当的消息?
$('#foo').editable({
type: 'text',
validate: function(value) {
//How do I use myValidateObj to validate foo and return applicable message???
}
});
Name: <a href="javascript:void(0)" id="foo"><?php echo($foo); ?></a>
Bla: <a href="javascript:void(0)" id="bar"><?php echo($bar); ?></a>
回答by Sparky
The .valid()
method can be used to force an immediate validation test of a single element.
该.valid()
方法可用于强制对单个元素进行即时验证测试。
$('#foo').valid();
http://jqueryvalidation.org/valid/
http://jqueryvalidation.org/valid/
FYI:
仅供参考:
The .validate()
method is onlyused for initializingthe plugin on your form, not for triggering tests. Therefore, you still need to call .validate()
once within DOM ready before you can use .valid()
.
该.validate()
方法仅用于初始化表单上的插件,不用于触发测试。因此,您仍然需要.validate()
在 DOM ready 内调用一次,然后才能使用.valid()
.