0

How can I set a bean validation constraint that a List should at minimum contain 1 and at maximum contain 4 elements, at the same time, check the maximum length of each elements

the following annotation only works for minItems, maxItems, while how to constrain the the maximum length of each elements

@Size(min=1, max=4) private List list;

"list": [ "String1", "String2", "String3" ]

Thanks

Neil
  • 1
  • 3
  • 1
    Welcome to stack overflow. Please take a peek at this Question/Answer and see if that helps: [How to validate the length of elements inside List using javax.validation.constraints in Spring](https://stackoverflow.com/q/49939444/42962) – hooknc Mar 15 '22 at 17:34
  • Does this answer your question? [How to validate the length of elements inside List using javax.validation.constraints in Spring](https://stackoverflow.com/questions/49939444/how-to-validate-the-length-of-elements-inside-list-using-javax-validation-constr) – hooknc Mar 15 '22 at 17:52

2 Answers2

0

Actually, the annotation will work on just the list of objects. So I suggest adding a new class and defining a String field that has a @Size(min= 10). Here is what I mean:

public class InputString{
       @Size(min = 10, message =  "{validation.name.size.too_long}")
       private String input;
}

Then use it:

@Size(min=1, max=4)
 private List<InputString> list;
m.bidkham
  • 1
  • 1
  • while the incoming json payload structure is : "StringList": ["String1", "String2", "String3"], can not change the element to Java object. – Neil Mar 15 '22 at 18:52
  • So you have to iterate the list and check the length of each String in a for each. – m.bidkham Mar 15 '22 at 18:59
0

It is possible to add a method to the object that will be part of the validation.

@AssertTrue
private boolean isList() {
    return list.stream().noneMatch(s -> s.length() > 20 || s.length() < 3);
}
Jeppz
  • 912
  • 1
  • 8
  • 31