使用jQuery validate插件为多个字段输出一条错误消息 [英] Using jQuery validate plugin to output a single error message for multiple fields

查看:205
本文介绍了使用jQuery validate插件为多个字段输出一条错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery validate插件来验证表单.所有字段都是必填字段,并且错误消息的空间在表格上受到限制,因此,如果我的规则中的任何字段都未填写,则有可能显示一条错误消息,提示所有字段必须在提交表单之前完成.形式"?

I'm using the jQuery validate plugin to validate a form. All fields are mandatory and space for error messages is limited on the form, so is it possible to show a single error message if any of the fields from my rules aren't completed which says, 'All fields must be completed before you submit the form' ?

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

My jQuery knowledge is limited and I can only figure from examples how to set it up so that it outputs individual error messages for each field using the following code:

$(".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" }
  },
});

推荐答案

这将满足您的要求:

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

尽管当有人输入错误的电子邮件地址时此错误消息不是很好,因为所有字段均已填写,但表格中仍然存在错误.

Although this error message isn't very good for when someone enters an incorrect email address, as all fields have been filled in but there is still an error in the form.

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

Also, note you can specify required fields in the form by setting their class attribute to 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

这篇关于使用jQuery validate插件为多个字段输出一条错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆