Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSR 303: How to Validate a Collection of annotated objects?

Is it possible to validate a collection of objects in JSR 303 - Jave Bean Validation where the collection itself does not have any annotations but the elements contained within do?

For example, is it possible for this to result in a constraint violation due to a null name on the second person:

List<Person> people = new ArrayList<Person>(); people.add(new Person("dave")); people.add(new Person(null));  Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<List<Person>>> validation = validator.validate(people); 
like image 571
cam Avatar asked Nov 05 '10 14:11

cam


People also ask

Which annotations is used for validation?

The @Valid annotation applies validation rules on the provided object. The BindingResult interface contains the result of validation.

How do you validate a list in Java?

list = new ArrayList<E>(); } public ValidList(List<E> list) { this. list = list; } // Bean-like methods, used by javax. validation but ignored by JSON parsing public List<E> getList() { return list; } public void setList(List<E> list) { this.

What is spring bean validation?

Bean Validation or commonly known as JSR-380 is a Java standard that is used to perform validation in Java applications. To perform validation, data Items are applied constraints. As long as the data satisfies these constraints, it will be considered valid.


1 Answers

Yes, just add @Valid to the collection.

Here is an example from the Hibernate Validator Reference.

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

This is standard JSR-303 behavior. See Section 3.1.3 of the spec.

like image 168
sourcedelica Avatar answered Sep 22 '22 00:09

sourcedelica