Search code examples
javahibernatevalidationannotationshibernate-validator

Duplicate annotation - hibernate validator


I would like to use one hiberante validator annotation multiple times on one property.

e.g:

@Length(min = 10, max = 10, groups = {Lenght10Group.class})
@Length(min = 5, max = 5, groups = {Lenght5Group.class})
private String productCode;

I've found the following thread Multiple annotations of the same type on one element? and tried to apply it to my application.

I created Lengths.java file:

public @interface Lenghts {
   Lenght[] value();
}

and applied it in the following way:

@Lenghts( {@Length(min = 10, max = 10, groups = {Lenght10Group.class}), 
           @Length(min = 5, max = 5, groups = {Lenght5Group.class}) })
private String productCode;

but it doesn't seem to work.

What am I missing? Is custom validator needed, a custom handler? Could anyone help me with this? I will be grateful.


Solution

  • You should use @Length.List which is provided by Hibernate Validator out of the box. All built-in constraints (both defined by the BV specification and additional custom constraints by Hibernate Validator) define such an @List annotation.