Search code examples
javaspring-mvcbean-validationhibernate-validator

How to make javax validation only display one error message


Say I have validation on a field like this:

@NotEmpty
@Digits(integer = 3, fraction = 0)
private String code;

Using Spring MVC and Hibernate validation currently I get both messages if I leave the form field blank. Is there a way to only display the @NotEmpty message?


Solution

  • If you want to stick to the Bean Validation Specification you need to use a group sequence. Only a groups sequence guarantees an ordered constraint evaluation which stops on the first error. Something like:

    @GroupSequence({ First.class, Second.class })
    public class MyBean {
       @NotEmpty(groups = First.class)
       @Digits(integer = 3, fraction = 0, groups = Second.class)
       private String code;
    }