I want to force user to send numeric value for a field in request, as user may enter char as well. Since I haven't found any built in solution in spring mvc validation, I chose to create my own custom validator to check the entered value is number or not. Please find below code snippet.
Constraint interface :
@Documented
@Constraint(validatedBy = {IntegerValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface IntegerConstraint {
String message() default "Please enter numers only...!!!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Validator class :
public class IntegerValidator implements ConstraintValidator<IntegerConstraint, String> {
@Override
public void initialize(IntegerConstraint contactNumber) {
}
@Override
public boolean isValid(String reqParam, ConstraintValidatorContext cxt) {
return !StringUtils.isEmpty(reqParam) && reqParam.matches("^(0|[1-9][0-9]*)$");
}
}
DTO class field :
@IntegerConstraint
@PositiveOrZero(message = "Sorting number either can be positive or zero...!!!")
private Integer sortOrd;
Controller :
public ModelAndView addDetail(@Valid @ModelAttribute("fooDetails") FooDTO footDTO,
BindingResult result, HttpServletRequest request)
Error log :
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'com.eps.customvalidator.IntegerConstraint' validating type 'java.lang.Integer'. Check configuration for 'sortOrd'
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getExceptionForNullValidator(ConstraintTree.java:108) ~[hibernate-validator-6.0.10.Final.jar:6.0.10.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:140) ~[hibernate-validator-6.0.10.Final.jar:6.0.10.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:55) ~[hibernate-validator-6.0.10.Final.jar:6.0.10.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:73) ~[hibernate-validator-6.0.10.Final.jar:6.0.10.Final]