0

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?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Somewhat related: [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) – GBlodgett Aug 27 '19 at 02:38

1 Answers1

4

Annotate the type, using this syntax:

List<@Min(1000) @Max(9999) Integer> numbers;
Bohemian
  • 412,405
  • 93
  • 575
  • 722