Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bean validation size of a List?

How can I set a bean validation constraint that a List should at minimum contain 1 and at maximum contain 10 elements?

None of the following works:

@Min(1) @Max(10) @Size(min=1, max=10) private List<String> list; 
like image 648
membersound Avatar asked May 22 '17 09:05

membersound


People also ask

How do you validate a list of objects in Java?

Your list subclass would look something like this: public class ValidList<E> implements List<E> { @Valid private List<E> list; public ValidList() { this. list = new ArrayList<E>(); } public ValidList(List<E> list) { this. list = list; } // Bean-like methods, used by javax.

What does @validated do?

The @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class.


1 Answers

I created simple class:

public class Mock {      @Size(min=1, max=3)     private List<String> strings;      public List<String> getStrings() {         return strings;     }      public void set(List<String> strings) {         this.strings = strings;     }  } 

And test:

Mock mock = new Mock(); mock.setStrings(Collections.emptyList()); final Set<ConstraintViolation<Mock>> violations1 = Validation.buildDefaultValidatorFactory().getValidator().validate(mock); assertFalse(violations1.isEmpty());  mock.setStrings(Arrays.asList("A", "B", "C", "D")); final Set<ConstraintViolation<Mock>> violations2 = Validation.buildDefaultValidatorFactory().getValidator().validate(mock); assertFalse(violations2.isEmpty()); 

It seems that @Size annotation is working well. It comes from javax.validation.constraints.Size

like image 191
ByeBye Avatar answered Oct 06 '22 07:10

ByeBye