如何仅在提交时显示jQuery Validation错误容器

时间:2008-11-12 21:23:05

标签: javascript jquery

我正在努力使Validation plugin工作。它适用于单个字段,但是当我尝试包含包含所有错误的错误容器的演示代码时,我遇到了问题。问题是,当我在所有字段中时,它显示容器包含所有错误,但我想仅在用户按下提交按钮时显示错误容器(但在失去焦点时仍然在控件旁边显示内联错误)。 / p>

问题是容器中的消息。当我在下面的答案中提到容器的代码时,容器输出只显示纯文本中的错误数。

获取详细错误消息列表的技巧是什么?我想要的是当用户按下标签按钮时在控件旁边显示“错误”,并在按下提交时在结尾处显示所有内容的摘要。这可能吗?

来自此处所有输入的代码:

    $().ready(function() {
        var container = $('div.containererreurtotal');

        // validate signup form on keyup and submit
        $("#frmEnregistrer").bind("invalid-form.validate", function(e, validator) {
          var err = validator.numberOfInvalids();
          if (err) {
            container.html("THERE ARE "+ err + " ERRORS IN THE FORM")
            container.show();
          } else {
            container.hide();
          }
        }).validate({
                    rules: {
                            nickname_in: {
                                    required: true,
                                    minLength: 4
                            },
                            prenom_in: {
                                    required: true,
                                    minLength: 4
                            },
                            nom_in: {
                                    required: true,
                                    minLength: 4
                            },
                            password_in: {
                                    required: true,
                                    minLength: 4
                            },
                            courriel_in: {
                                    required: true,
                                    email: true
                            },
                            userdigit: {
                                    required: true
                            }
                    },
                    messages: {
                            nickname_in: "ERROR",
                            prenom_in: "ERROR",
                            nom_in: "ERROR",
                            password_in: "ERROR",
                            courriel_in: "ERROR",
                            userdigit: "ERROR"
                    }

                    ,errorPlacement: function(error, element){
                            container.append(error.clone());
                            error.insertAfter(element);
                    }

            });
    });

6 个答案:

答案 0 :(得分:16)

首先你的容器应该使用ID而不是类..(我将假设ID是'containererreurtotal')

然后试试这个..

    $().ready(function() {

        $('div#containererreurtotal').hide();

        // validate signup form on keyup and submit
        $("#frmEnregistrer").validate({
            errorLabelContainer: "#containererreurtotal",
            wrapper: "p",
            errorClass: "error",
            rules: {
                nickname_in: { required: true, minLength: 4 },
                prenom_in: { required: true, minLength: 4 },
                nom_in: { required: true, minLength: 4 },
                password_in: { required: true, minLength: 4 },
                courriel_in: { required: true,  email: true },
                userdigit: { required: true }
            },
            messages: { 
                nickname_in: { required: "Nickname required!", minLength: "Nickname too short!" },
                prenom_in: { required: "Prenom required!", minLength: "Prenom too short!" },
                nom_in: { required: "Nom required!", minLength: "Nom too short!" },
                password_in: { required: "Password required!", minLength: "Password too short!" },
                courriel_in: { required: "Courriel required!", email: "Courriel must be an Email" },
                userdigit: { required: "UserDigit required!" }
            },
            invalidHandler: function(form, validator) {
                $("#containererreurtotal").show();
            },
            unhighlight: function(element, errorClass) {
                if (this.numberOfInvalids() == 0) {
                    $("#containererreurtotal").hide();
                }
                $(element).removeClass(errorClass);
            }    

        });
    });

我在这里假设你想要一个< p>标记每个错误。通常我使用< ul>实际容器的容器(而不是您使用的称为'containererreurtotal'的div)和< li>对于每个错误(此元素在“包装器”行中指定)

如果指定#containererreurtotal为display:none;在你的CSS中,你不需要就绪函数中的第一行($('div#containererreurtotal')。hide();)

答案 1 :(得分:14)

您可以在http://docs.jquery.com/Plugins/Validation/validate#toptions

中找到meta选项的文档

如果您想在单独的错误容器中显示输入 AND 旁边的错误,则需要覆盖errorPlacement回调。

从你的例子:

...
                    courriel_in: "ERROR",
                    userdigit: "ERROR"
            }
            ,errorContainer: container

            ,errorPlacement: function(error, element){
                var errorClone = error.clone();
                container.append(errorClone);
                error.insertAfter(element)              
            }

            // We don't need this options
            //,errorLabelContainer: $("ol", container)
            //,wrapper: 'li'
            //,meta: "validate"
    });
 ...

error参数是一个包含<label>标记的jQuery对象。 element参数是验证失败的输入。

更新评论

使用上面的代码,错误容器不会清除错误,因为它包含克隆的副本。如果jQuery给出一个“隐藏”事件,它很容易解决,但它不存在。让我们添加一个隐藏事件!

  1. 首先我们需要AOP plugin
  2. 我们为hide方法添加了一条建议:

                jQuery.aop.before({target: jQuery.fn, method: "hide"},
                    function(){
                        this.trigger("hide");
                    });
    
  3. 我们绑定hide事件以隐藏克隆的错误:

            ...
            ,errorPlacement: function(error, element){
                var errorClone = error.clone();
                container.append(errorClone);
                error.insertAfter(element).bind("hide", function(){
                    errorClone.hide();
                });
            }
            ...
    
  4. 试一试

答案 2 :(得分:3)

我会删除errorContainer,然后在回发时拦截验证,并在那里手动添加容器错误,如下所示:

$("#frmEnregistrer").bind("invalid-form.validate", function(e, validator) {
  var err = validator.numberOfInvalids();
  if (err) {
    container.html("THERE ARE "+ err + " ERRORS IN THE FORM")
    container.show();
  } else {
    container.hide();
  }
}).validate({ ... })

答案 3 :(得分:3)

我的解决方案略有不同:

jQuery(document).ready(function() {
  var submitted = false;
  var validator = jQuery("#emailForm").validate({ 
      showErrors: function(errorMap, errorList) {
          if (submitted) {
              var summary = "";
              jQuery.each(errorList, function() {
              summary += "<li><label for='"+ this.element.name;
              summery += "' class='formError'>" + this.message + "</label></li>"; });
              jQuery("#errorMessageHeader").show();
              jQuery("#errorMessageHeader").children().after().html(summary);
              submitted = false;
          }
          this.defaultShowErrors();
      },          
      invalidHandler: function(form, validator) { submitted = true; },
      onfocusout: function(element) { this.element(element); },
      errorClass: "formError",
      rules: { 
          //some validation rules 
      },
      messages: { 
          //error messages to be displayed
      }           
  }); 
}); 

答案 4 :(得分:2)

我用以下简短代码解决了这个问题:

errorElement: "td",
errorPlacement: function (error, element) {
     error.insertAfter(element.parent());
} 

我的结构如下:

<table>
   <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
   </tr>
</table>

因此,我的错误现在会直接显示在<td>

后面的<input>

答案 5 :(得分:-1)

我不知道验证插件是否为此提供了一个选项,但你可以使用标准的jQuery来实现你想要的。通过将显示样式设置为none来确保最初隐藏容器:

<div id="container" style="display:none;"></div>

然后,您可以将onsubmit事件连接到表单,只要尝试提交表单,就会立即显示容器:

jQuery('#formId').onsubmit(function() {
    // This will be called before the form is submitted
    jQuery('#container').show();
});

希望将其与现有代码相结合应该可以解决问题。