问题
The validate plugin seems to be eagerly validating on a custom method I have when it should be lazy, all other validation occurs lazily (i.e. not until the form is submitted).
The custom method:
$.validator.addMethod("refDataAcInput", function(value, element)
{
return ($(element).val() == "" || $(element).data("hasValidSelectedValue") != null);
}, "The item must be a valid selected item.");
Validate plugin init:
this.$form.validate({
ignore: null,
invalidHandler : function()
{
_self.initUnsavedChangesWarning.ignorePageLeaveReq = false;
_self.setValidationMsgVisible(true);
$("body,html").scrollTop($("#cmFormErrorReport").position().top);
},
submitHandler :function(form)
{
//Disable form submit button - prevent duplicate request for impatient users
$("button[type=submit]", form).prop("disabled", true);
form.submit();
},
showErrors : function(errorMap, errorList)
{
_self.updateErrors(errorList);
this.defaultShowErrors();
},
errorPlacement : function(error, $element)
{
$element.parents("tr").children(".fieldError").append(error);
},
errorClass : "jqueryError"
});
Any ideas how to make this occur lazily?
回答1:
The problem is that you've built the required rule into your custom method.
$.validator.addMethod("refDataAcInput", function(value, element) {
return ($(element).val() == "" || $(element).data("hasValidSelectedValue") != null);
}, "The item must be a valid selected item.");
Remove $(element).val() == "" and replace with this.optional(element)...
$.validator.addMethod("refDataAcInput", function(value, element) {
return (this.optional(element) || $(element).data("hasValidSelectedValue") != null);
}, "The item must be a valid selected item.");
Then if you also want the field to be required, just declare the required rule along with your custom refDataAcInput rule.
The plugin's default "Lazy" validation should now be working as expected.
来源:https://stackoverflow.com/questions/10294270/jquery-validate-plugin-eager-validation-on-custom-method-when-should-be-lazy