Handle validation for non numeric characters getting passed to Integer variable

484 views Asked by At

Is there an annotation that could be used to prevent the following error from getting thrown by my Java application if I send a non numerical value for year in my GET request?

I currently have this:

@NotNull
@Digits(integer = 4, fraction = 0, message = "Provide valid Year in the format YYYY")
@Min(value = 1900, message = "Year must be greater than 1900")
private Integer year;

When I pass a value with letters I get a NumberFormatException before @Digits and @Min is executed. I also tried @Pattern with a regex value but that caused a 500 error.

"Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'yearOfReg'; nested exception is java.lang.NumberFormatException: For input string: \"20c15\"
1

There are 1 answers

0
Rob Spoor On

The answer is very short: no. That's because the validation is configured for the Integer year field. That means that the field must get populated before it can be validated. That population fails if you submit a value that cannot be parsed to an Integer.

The best way to handle this case is to add error handling for the mapping exception. For Jackson that's a MismatchedInputException.

An alternative is to change the field to a String. That allows you to use @Pattern, but you will need to convert yourself. That can be done in the class itself using a getter.