本文介绍了带有jQuery的.validate表单-同时使用errorPlacement和showErrors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Jquery .validate插件进行验证.

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

我不能同时使用errorPlacement和showErrors方法.

I can't use errorPlacement and showErrors methods together.

JsFiddle:工作错误位置- http://jsfiddle.net/5RrGa/1861/

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

正在运行的showErrors- http://jsfiddle.net/5RrGa/1862/

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();
    }
});

当我删除showErrors时,errorPlacement可以正常工作.如果我尝试使用showErrors,它将跳过errorPlacement.

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

如果我将showErrors放在errorPlacament之前没有任何变化,则errorPlacement仍然无法正常工作.

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

如何使两种方法协同工作?

How to make both methods to work together?

推荐答案

您可以执行以下操作:

$(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) {
        }
    });
  });

提琴: http://jsfiddle.net/maverickosama92/5RrGa/1863/

这篇关于带有jQuery的.validate表单-同时使用errorPlacement和showErrors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 09:29