Bean validation size of a List?
Asked Answered
C

2

44

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;
Corneliuscornell answered 22/5, 2017 at 9:3 Comment(1)
For me, @Size works perfectly. Can you show us code where you validating it? Did you use import javax.validation.constraints.Size?Disorient
D
70

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

Disorient answered 22/5, 2017 at 9:25 Comment(2)
Got it: I'm using spring-mvc, and the validation is only applied on the List if the list is defined at all in the input parameters (I just left out the list in my request, because I set min=1). Solution is to use @NotNull @Size in conjunction if the list should always exist and have at least a single item.Corneliuscornell
@SledgeHammer can you open another question and put some code that is not working to check it?Disorient
M
13

You can use @NotEmpty to check for empty list. This make sure there is at least one item in list.

Moniz answered 20/3, 2018 at 19:11 Comment(4)
@NotEmpty can only be applied to pain String.Corneliuscornell
From Hibernate validator doc: @NotEmpty Supported data types CharSequence, Collection, Map and arraysSera
As Hibernate @NotEmpty annotation is deprecated, you should now use javax.validation.constraints.NotEmptyWimble
jakarta.validation.constraints.NotEmpty can be applied many cases: 1) CharSequence (length of character sequence is evaluated) 2) Collection (collection size is evaluated) 3) Map (map size is evaluated) 4) Array (array length is evaluated)Kutzenco

© 2022 - 2024 — McMap. All rights reserved.