Paweł Kaczorowski
Paweł Kaczorowski

Reputation: 1562

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 ?

Upvotes: 1

Views: 51

Answers (2)

Hardy
Hardy

Reputation: 19129

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.

Upvotes: 1

Maroun
Maroun

Reputation: 96018

I would simply wrap the class:

class MyString {

    @SomeCustomStringValidator
    String bar;

    // mutators
}

Then construct a list of MyString:

class Foo {
    List<MyString> bars;
}

Upvotes: 1

Related Questions