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?
Bean Validation doesn’t offer an API for directly validating collections. Only the cascaded validation of collections/arrays using
@Validis supported.The
validate()method you’re using validates the constraints declared on the type of the passed object. There are no constraints declared onListorArrayList, that’s why no constraint violations occure when passing a list directly tovalidate().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).