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

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

Forcing jQuery validator to validate a single element

javascriptjqueryjquery-validatex-editable

提问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 myValidateObjobject exists on this page, can it be used to validate a single field? For instance, within the editable validate callback, how can myValidateObjbe used to validate fooand 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().