Custom error messages for groups in jQuery validation plugin

I am using the jQuery Validation plugin and I started grouping some of my fields together:

groups: { fullName: "myFirstName myLastName" }, 

I also added fields to the rules section so that they are checked:

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

This works fine and gives a "This field is required" error for the group.

My question is about custom error messages. I have the following setup:

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

Unfortunately, the user error is not displayed, only a general one.

Does anyone have any ideas?

+7
javascript jquery jquery-validate validation messages
source share
1 answer

For this you need to use errorPlacement , and the message should be the same for 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, if they have the same identifiers, your errorPlacement parameter will 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 just tells the plugin that they have a message label.

+11
source share

All Articles