Using groups with jquery form validation. How?

I was looking at a list of available options for the jquery form validation plugin ( http://docs.jquery.com/Plugins/Validation/validate#toptions ). I connect to understand how groups work. The only code available on the official (?) Website:

// Use a table layout for the form, placing error messages in the next cell after the input. $("#myform").validate({ groups: { username: "fname lname" }, errorPlacement: function(error, element) { if (element.attr("name") == "fname" || element.attr("name") == "lname" ) error.insertAfter("#lastname"); else error.insertAfter(element); }, debug:true }) 

I understand that they create a group called "username" that groups two elements in the form: "fname" and "lname", but how is this group used? Actually, the first question I have is this: what are the groups for? I thought that this should give the plugin a command to treat the elements in the group as a whole, and also display a single error if one of the elements triggers one (for example, if two text fields are marked as required using rules , and if the value is missing in any of two or two of them, then instead of two, if two elements have errors, one error label is displayed, but I try several examples and could not get it to work this way. So, what are they for? how to use them?

+4
source share
1 answer

The sum of what the groups option does is to report only one error message for all things within the group. In this example, if you did not group fname and lname , and both of them were necessary, then you would receive two error messages. With a group you get only one. Both elements of the group are still required.

It sounds like you get it right, but it's hard to say why you are not getting this example to work. Using this HTML:

 <form id="myform"> First Name: <input type="text" name="fname" id="fname"/><br> Last Name: <input type="text" name="lname" id="lname"/><br> <input type="submit"/> </form>​ 

And this confirmation code:

 $("#myform").validate({ rules: { fname: { required: true }, lname: { required: true } }, groups: { username: "fname lname" }, errorPlacement: function(error, element) { if (element.attr("name") == "fname" || element.attr("name") == "lname" ) error.insertAfter("#lname"); else error.insertAfter(element); } })​ 

I'm fine: http://jsfiddle.net/ryleyb/cbJj6/

A more sophisticated example that I helped someone is here: Using the jQuery validation plugin to check if one or more of the checkboxes (with different names) is selected The checkbox was checked, and only one message was requested if it weren’t.

+6
source

All Articles