使用jQuery validate plugin为多个字段输出单个错误消息

时间:2012-12-05 05:05:12

标签: jquery jquery-validate

我正在使用jQuery validate插件来验证表单。所有字段都是必填字段,并且错误消息的空间在表单上受到限制,因此如果我的规则中的任何字段未完成,则可以显示单个错误消息,其中说:“所有字段必须在您提交之前完成形式'?

我的jQuery知识有限,我只能从示例中了解如何设置它,以便使用以下代码为每个字段输出单独的错误消息:

$(".contact-form").validate({
  errorLabelContainer: ".form-errors",
  wrapper: "li",
  ignore: ".ignore",
  errorElement: "em",
  rules: {
    first_name: { required: true },
    last_name: { required: true },
    email: { required: true, email: true }
  },
  messages: {
    first_name: "Please enter your first name",
    last_name: "Please enter your last name",
    email: { required: "Please enter your email address", email: "Your email address must be in the format of name@domain.com" }
  },
});

4 个答案:

答案 0 :(得分:7)

这将满足您的要求:

<强>的Javascript

$(".contact-form").validate({
    ignore: ".ignore",
    rules: {
        first_name: {
            required: true
        },
        last_name: {
            required: true
        },
        email: {
            required: true,
            email: true
        }
    }, 
    showErrors: function(errorMap, errorList) {
        $(".form-errors").html("All fields must be completed before you submit the form.");
    }
});​

<强> Demo

虽然当有人输入错误的电子邮件地址时,此错误消息不是很好,因为所有字段都已填写但表单中仍有错误。

另请注意,您可以通过将class属性设置为required来指定表单中的必填字段:

<强> HTML

<form class="contact-form" type="post" action="">
    <input type="text" name="first_name" id="first_name" class="required" />
    <input type="text" name="last_name" id="last_name" class="required" />
    <input type="email" name="email" id="email" class="required email" />
    <input type="submit" />
    <div class="form-errors"></div>
</form>​

<强>的Javascript

$(".contact-form").validate({
    showErrors: function(errorMap, errorList) {
        $(".form-errors").html("All fields must be completed before you submit the form.");
    }
});​

<强> Demo

答案 1 :(得分:3)

看起来 invalidHandler 就是您所需要的。看一下这个例子(来源:http://docs.jquery.com/Plugins/Validation/validate#toptions):

$(".selector").validate({
   invalidHandler: function(form, validator) {
  var errors = validator.numberOfInvalids();
  if (errors) {
    var message = errors == 1
      ? 'You missed 1 field. It has been highlighted'
      : 'You missed ' + errors + ' fields. They have been highlighted';
    $("div.error span").html(message);
    $("div.error").show();
  } else {
    $("div.error").hide();
  }
}
})

答案 2 :(得分:2)

fxnReqValidation = function (event) {
        $("#errormsg").empty();
        $("input:text").each(function (index, InputElement) {
            var Ele = g_Json[InputElement.name];
            if ((Ele.required) && (InputElement.value == "" || null)) {
                $("#errormsg").append("" + All fields must be completed before you submit the form + "");                
            }           
        });
        event.preventDefault();
    }

这可能对你有帮助。

答案 3 :(得分:0)

您可以使用toggle()方法在消息之间切换并使用jquery插件...它认为它更快更容易编码......