问题
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