JQuery Validate Plugin - Eager validation on custom method when should be lazy

早过忘川 提交于 2019-12-12 14:42:09

问题


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

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