Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 449
Limbo Exile Avatar asked Feb 21 '17 08:02

Limbo Exile


People also ask

How do you accept only numbers in Java?

To only accept numbers, you can do something similar using the Character. isDigit(char) function, but note that you will have to read the input as a String not a double , or get the input as a double and the converting it to String using Double. toString(d) .

What is the difference between @valid and validated?

The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.

What is Spring Validator?

Spring features a Validator interface that you can use to validate objects. The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.


1 Answers

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})
like image 65
john16384 Avatar answered Sep 21 '22 12:09

john16384