Siarhei Vouchak
Siarhei Vouchak

Reputation: 125

Validate Collection using JSR 303

I want to validate array of beans using JSR 303 Validation. Like spec says, it's possible to validate the whole collection. if I had object like this

public class Car {
  @NotNull
  @Valid
  private List<Person> passengers = new ArrayList<Person>();
}

so I would be able to validate list of passengers by doing following:

Car car = ....
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Car>> validation = validator.validate(car);

But I wondering, why can't I validate list of passengers by doing following:

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<List<Person>>> validation =validator.validate(passengers);

It just doesn't work! Can anybody give me any explanations on that?

Upvotes: 2

Views: 2332

Answers (1)

Gunnar
Gunnar

Reputation: 18980

Bean Validation doesn't offer an API for directly validating collections. Only the cascaded validation of collections/arrays using @Valid is supported.

The validate() method you're using validates the constraints declared on the type of the passed object. There are no constraints declared on List or ArrayList, that's why no constraint violations occure when passing a list directly to validate().

You could either iterate over the passenger list and validate the individual elements or validate a object owning the list (as in your original example).

Upvotes: 2

Related Questions