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.