Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom error messages for Groups within the jQuery Validation plugin

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?

like image 667
Richard L Avatar asked Dec 10 '10 12:12

Richard L


1 Answers

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.

like image 86
Nick Craver Avatar answered Oct 04 '22 20:10

Nick Craver