Search code examples
javahibernatejpahibernate-validator

Collection validation from single validator


Lets say that I have a class:

class Foo{
  @SomeCustomStringValidator
  String bar;
}

and then I would like to have

class Foo{

  List<String> bars;
}

Is there any way to use somehow @SomeCustomStringValidator to be applied on the bars collection ?


Solution

  • If you are using Java 8, you could use the latest Hibernate Validator 5.2 version. There is is possible to do:

    class Foo{
      @Valid
      List<@SomeCustomStringValidator String> bars;
    }
    

    Otherwise you could use the class wrapping approach as mentioned in this answer.

    Last but not least, you could write a custom ConstraintValidator<SomeCustomStringValidator, Collection> and try sharing the core validation logic between this validator and the `ConstraintValidator you already have.