Forcing jQuery validator to validate a single element

巧了我就是萌 提交于 2019-12-13 19:35:53

问题


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>

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>

回答1:


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

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

http://jqueryvalidation.org/valid/


FYI:

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().



来源:https://stackoverflow.com/questions/29542425/forcing-jquery-validator-to-validate-a-single-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!