Search code examples
javaspringcollectionsjavax.validation

How to apply validation to elements of a collection type


I'm using spring, and thus javax.validation, so that's context of this question.

Suppose I want to validate that the elements of a list only contain 4 digit numbers.

I would like to code:

@Min(1000)
@Max(9999)
List<Integer> numbers;

but validation explodes complaining that @Min and @Max can't be used to validate a List. OK, makes sense.

I could use @Valid on a list of custom objects, eg:

@Valid // validate each element
List<My4DigitNumberClass> numbers;

@MyCustom4DigitValidation
class My4DigitNumberClass {
    Integer number;
}

but I just want to use Integer (and eventually other boxed primitives, Strings, etc), something like:

@ValidateElements({ @Min(1000), @Max(9999) })
List<Integer> numbers;

Can I do this without creating any custom classes or custom validation annotations?


Solution

  • Annotate the type, using this syntax:

    List<@Min(1000) @Max(9999) Integer> numbers;