What is the idea of using groups in Bean Validation

906 views Asked by At

What is the idea of using groups in short? For example, the class definition has no groups now. What's going to change if we enable groups below?

//  @Size(min = 4, max = 30, groups = LengthGroup.class)
    @Size(min = 4, max = 30)
    private String name;

//  @Size(min = 12, max = 120, groups = LengthGroup.class)
    @Size(min = 12, max = 120)
    private String address;

//  @Size(min = 5, max = 30, groups = LengthGroup.class)
    @Size(min = 5, max = 30)
    @EmailAddress//(groups = EmailGroup.class)
    private String email;

p.s. there are also two corresponding interfaces for those groups

2

There are 2 answers

0
Konstantin Yovkov On BEST ANSWER

It is often useful to declare the same constraint more than once to the same target, with different properties. That's what the group is about. Consider this example:

public class Address {
    @ZipCode.List( {
            @ZipCode(countryCode="fr", groups=Default.class
                     message = "zip code is not valid"),
            @ZipCode(countryCode="fr", groups=SuperUser.class
                     message = "zip code invalid. Requires overriding before saving.")
            } )
    private String zipcode;
}

In this example, both constraints apply to the zipcode field but with different groups and with different error messages.

Example taken from here.

0
wonderb0lt On

In addition what kocko said, they are also meant to categorize validation rules. Quoting from the JSR-303 final spec:

Groups allow you to restrict the set of constraints applied during validation.

If you re-add the groups mentioned above and call the validatior like this: validator.validate(user, LengthGroup.class);, the lengths of your fields only will be validated. This means that the @EmailAddress constraint is not taken into consideration.

If you call the validator like this: validator.validate(user, LengthGroup.class, EmailGroup.class);, all your constraints will be validated against.

A use-case more intended for this feature would be validation a version of the user with contact data, and one without. Consider the folling example:

@Size(min = 4, max = 30)
private String name;

@Size(min = 12, max = 120, groups=WithContactInfo.class)
private String address;

@Size(min = 5, max = 30, groups= WithContactInfo.class)
@EmailAddress(groups = WithContactInfo.class)
private String email;

Now you could validate a user that does not need to have contact info with validator.validate(user), and a user that needs to have contact info too with validator.validate(user, WithContactInfo.class).