强制jQuery验证程序验证单个元素 [英] Forcing jQuery validator to validate a single element

查看:87
本文介绍了强制jQuery验证程序验证单个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编辑页面上,我正在使用 http://jqueryvalidation.org/来验证表单.

On an edit page, I am using http://jqueryvalidation.org/ to validate a form.

//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>

在另一页面上,我正在显示先前描述的编辑页面的值,并允许使用 http://vitalets.github.io/x-editable/.验证规则和消息仍然适用,但是现在仅需要验证单个字段.假设myValidateObj对象存在于此页面上,可以将其用于验证单个字段吗?例如,在可编辑的validate回调中,如何使用myValidateObj来验证foo并在未通过验证时返回适当的消息?

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?

$('#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>

推荐答案

.valid()方法可用于强制对单个元素进行立即验证测试.

The .valid() method can be used to force an immediate validation test of a single element.

$('#foo').valid();

http://jqueryvalidation.org/valid/

仅供参考:

.validate()方法仅用于 ,用于 初始化 表单上的插件,而不用于触发测试.因此,在使用.valid()之前,仍然需要在DOM中调用一次.validate().

The .validate() method is only used for initializing the plugin on your form, not for triggering tests. Therefore, you still need to call .validate() once within DOM ready before you can use .valid().

这篇关于强制jQuery验证程序验证单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆