Control validation annotations order?

Mahmoud Saleh picture Mahmoud Saleh · Apr 6, 2011 · Viewed 16.9k times · Source

A field has two validation annotations

@NotEmpty
@Length(min=3,max=100)
String firstName;

Observation

If that field is left empty, then the resulting violations vary in order:

  • sometimes the @NotEmpty is violated first
  • other times the @Length is violated first

Questions

How does Hibernate specify the order in which validations (annotations) are processed? Can this validation order be customized?

Thanks in advance.

Answer

Wilhelm Kleu picture Wilhelm Kleu · Apr 7, 2011

Use JSR-303 validation groups.

If no groups are specified a constraint is part of the Default Bean Validation group (see: javax.validation.groups.Default).

Create an interface to be your "Extended" (or whatever you want to call it) group:

public interface Extended{}

Now create an interface that will have the javax.validation.GroupSequence annotation.

@GroupSequence({Default.class, Extended.class})
public interface MySequence {}

Set the validation groups on your constraints

@NotEmpty // If no group is specified it is part of the default group
@Length(min=3,max=100, groups = Extended.class)
String firstName;

Pass MySequence to your validator call.

validator.validate(object, MySequence.class);

As specified by your @GroupSequence the default constraints will be validated first and if no contraint violations are encountered it will move on to the extended group.