Search code examples
javaspringvalidationuser-inputhibernate-validator

Validator that must accept only specific numeric values


I am using Hibernate Validator in addition to javax.validation library to validate request bodies of controllers in a Spring MVC application. There are annotations for constraints that help with min and max boundaries and also with the number of digits but I couldn't find a way to accept only specific numbers. For example what if I only want to accept values 10, 20 and 50?

I'm aware that it's possible to use org.springframework.validation.Validator interface to create more complex rules. Another thing that came to mind is to create an enum with desired numeric values but it doesn't seem like a clean solution. I'm curious to know if there is a better, simpler way to achieve what I want.


Solution

  • You can create your own annotation that accepts multiple values. This involves writing an Annotation class and a Validator class:

    public class OneOfValidator implements ConstraintValidator<OneOf, Integer> {}
    

    And the annotation:

    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Constraint(validatedBy = OneOfValidator.class)
    public @interface OneOf {
        String message() default "value must match one of the values in the list";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
        int[] value() default {};
    }
    

    You could then use it like:

    @OneOf({2, 3, 5, 9})