Form .validate with jquery - use both errorPlacement and showErrors

∥☆過路亽.° 提交于 2019-12-25 04:16:02

问题


I am trying to make validation with Jquery .validate plugin.

I can't use errorPlacement and showErrors methods together.

JsFiddle: Working errorPlacement - http://jsfiddle.net/5RrGa/1861/

Working showErrors - http://jsfiddle.net/5RrGa/1862/

I need to combine them both to work together.

$("#form").validate({
    ignore: [],
    errorPlacement: function(error, element) {
        // if showErrors exists, this block is skipped. 
        error.insertAfter(element);
    },
    showErrors: function(errorMap, errorList){
        for (var i = 0; errorList[i]; i++) {
           var errorElement = this.errorList[i].element['attributes']['field']['value'];
           $('#allErrors').append("<p>" + errorElement + "</p>");
        }
    },
    submitHandler: function(form) {
        // Submit the form
        form.submit();
    },
    invalidHandler: function(event, validator) {
        // Show message with errors 
        $('#errordiv').show();
    }
});

When i remove showErrors, errorPlacement works perfect. If I try to use showErrors it skips errorPlacement.

If I put showErrors before errorPlacament nothing changes, errorPlacement still don't work.

How to make both methods to work together?


回答1:


Both works with

showErrors: function(errorMap, errorList){
    this.defaultShowErrors();
},



回答2:


You could do this:

$(document).ready(function(){
    $("#registerForm").validate({
        errorPlacement: function(error, element) {
            error.insertAfter(element);
        },
        showErrors: function(errorMap, errorList){
                var $errorDiv = $("#errordiv").empty().show();            
            this.defaultShowErrors();
            var errorsCombined = "";
            for(var el in errorMap){
                    errorsCombined += "<b>"+ el + "</b>" + errorMap[el]+"<br/>";
            }
            $errorDiv.append(errorsCombined);
        },
        submitHandler: function(form) {
            // Submit the form
            form.submit();
        },
        invalidHandler: function(event, validator) {
        }
    });
  });

Fiddle: http://jsfiddle.net/maverickosama92/5RrGa/1863/



来源:https://stackoverflow.com/questions/40170848/form-validate-with-jquery-use-both-errorplacement-and-showerrors

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