jQuery Validation插件中的组的自定义错误消息 [英] Custom error messages for Groups within the jQuery Validation plugin

查看:95
本文介绍了jQuery Validation插件中的组的自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery Validation插件,我开始将我的一些字段组合在一起:

I'm using the jQuery Validation plugin and i've started to group some of my fields together:

groups: {
fullName: "myFirstName myLastName"
},

我也是将字段添加到规则部分以便验证它们:

I've also added the fields to the rules section so that they are validated:

rules: {
myFirstName: {
required: true
},
myLastName: {
required: true
}
},

这很有效,并为该组产生此字段是必需的错误。

This works great and produces an error of "This field is required" for the group.

我的问题在于自定义错误消息。我有以下设置:

My question lies with custom error messages. I have the following setup:

messages: {
fullName: "Please enter both your first name and your last name"
}

不幸的是,自定义错误没有显示,只显示通用错误。

Unfortunately the custom error doesn't show, only the generic one.

有没有人有任何想法?

推荐答案

你必须使用 errorPlacement 为此,两者的消息应该相同,例如:

You have to use errorPlacement for this, and the message should be the same on both, for example:

messages: { 
  myFirstName: { required: "Please enter both your first name and your last name" },
  myLastName: { required: "Please enter both your first name and your last name" }
}

然后,假设他们在这里有相同的ID,你的 errorPlacement 选项如下所示:

Then, assuming they have the same IDs here, your errorPlacement option would look like this:

errorPlacement: {
  var n = element.attr("name");
  if (n == "myFirstName" || n == "myLastName")
    error.insertAfter("#myLastName");
  else
    error.insertAfter(element);
}

该组本身没有消息,它只是告诉插件他们共享一个消息标签。

The group itself has no message, it's just telling the plugin that they share a message label.

这篇关于jQuery Validation插件中的组的自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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