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.
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) .
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.
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.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With