I am using javax.validation
for validating request in an API developed using spring.
I have to validate List<Integer>
so that all values must be a positive number and size of the list must be exactly equal to some fix number e.g. 2.
public class RequestPoJo { private List<Integer> values; }
Valid request should be [ 1,2]
Invalid request should be [-1,2] or [1,2,3]
Advertisement
Answer
EDIT:
Just realized how you want to get your payload. In that case I think best would be to write your own constraint validator (annotation):
Annotation:
import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @NotNull @Size(min = 2, max = 2) @Target( { METHOD, FIELD, ANNOTATION_TYPE, PARAMETER}) @Retention(RUNTIME) @Constraint(validatedBy = {ValidRequestArrayValidator.class}) @Documented public @interface ValidRequestArray { String message() default "{com.mycompany.constraints.ValidRequestArray}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
Validator:
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; public class ValidRequestArrayValidator implements ConstraintValidator<ValidRequestArray, List<Integer>> { @Override public boolean isValid(List<Integer> value, ConstraintValidatorContext context) { return value.stream().noneMatch(n -> n < 0); } }
RestController:
@RestController @Validated public class TestController @RequestMapping("/test") void test( @RequestBody @ValidRequestArray List<Integer> values) throws JsonProcessingException { System.out.println(new ObjectMapper().writeValueAsString(values)); } }