27

I can't figure out how jquery validation groups work, nor how they should work.

I assumed it would serve as to validate conditions that needed more than one element to be tested, is that it?

Couldn't find anything about it on the jquery validation docs...

ekad
  • 14,436
  • 26
  • 44
  • 46
Rodrigo Gama
  • 1,092
  • 2
  • 13
  • 23

1 Answers1

36

The main purpose I have used groups for is to produce one error message for a group of inputs and their respective validation conditions.

For example if you want someones full name including title, first, and last name:

<script type="text/javascript">
  $('#yourform').validate({
    //...Your valid logic...
    groups: {
      nameGroup: "title firstName lastName"
    },
    rules: {
      title: "required",
      firstName: "required",
      lastName: "required"
    },
    messages: {
      title: "Full name is required",
      firstName: "Full name is required",
      lastName: "Full name is required"
    }
  });
</script>

<form id="yourform">
   <div>
    <input type="text" id="title" name="title" />              
    <input type="text" id="firstName" name="firstName" />              
    <input type="text" id="lastName" name="lastName" />   
  </div>
</form>

You still have to define the individual rules for these fields, in this case required and its custom message. The only difference being that if one or all of them failed validation it outputs one message. As far as I know the group name, eg: 'nameGroup' is not usable outside of the group function.

Hope this helps.

Mixchange
  • 893
  • 1
  • 8
  • 14
argonaut36
  • 461
  • 6
  • 9
  • 1
    Please note that in order for the `groups` feature to work, the other fields inside the groups needs to have been validated at lease once to be considered part of the group. You can call `$('#yourform').valid()` when the page is loaded to process all fields at once for instance. – ZeWaren Jan 03 '19 at 18:14