jQuery Validation - get list of erroneous fields in invalidHandler

跟風遠走 提交于 2020-01-01 01:53:13

问题


I'm using jQuery Validation on a page. During the call to the invalidHandler I would like to be able to access a list of all the form elements that failed validation.

This function is being passed as one of the options to the jQuery.validate() method...

invalidHandler: function (form) {
    var validator = $("#AddEditFinancialInstitutionForm").validate();
    validator.showErrors();
    console.log(validator);
}

I'm trying to find this information somewhere in the resulting validator object, but I can't seem to find it. Is there another way I can access this information?

Thanks


回答1:


In the invalidHandler, you are passed two arguments, a jQuery.Event and the validator object. You don't need to call validate within your invalidHandler to get the validate object. Further, the validator object has a properties called errorList and errorMap, which contain the information you are looking for.

invalidHandler: function(e,validator) {
    //validator.errorList contains an array of objects, where each object has properties "element" and "message".  element is the actual HTML Input.
    for (var i=0;i<validator.errorList.length;i++){
        console.log(validator.errorList[i]);
    }

    //validator.errorMap is an object mapping input names -> error messages
    for (var i in validator.errorMap) {
      console.log(i, ":", validator.errorMap[i]);
    }
}



回答2:


If you are using the default error class and only find the invalid elements, use

 $(this).find("input.error") // inside invalidHandler



回答3:


use this for getting errored field's whole element and it's attributes.

  var formerrorList = $("#FORM_ID_HERE").data("validator").errorList;
        $.each(formerrorList, function (key, value) {
            console.log(formerrorList[key].element.id);
        });


来源:https://stackoverflow.com/questions/11640189/jquery-validation-get-list-of-erroneous-fields-in-invalidhandler

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