Custom error messages for Groups within the jQuery Validation plugin

浪尽此生 提交于 2020-01-02 03:12:09

问题


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.

Does anyone have any ideas?


回答1:


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" }
}

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.



来源:https://stackoverflow.com/questions/4408689/custom-error-messages-for-groups-within-the-jquery-validation-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!