Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @Digits validation on integer value

I want to validate if incoming number is integer value (wihout fraction), between 0 and 100.

I have dto with javax.validation annotations:

@Min(value = 1, message = "some msg")
@Max(value = 100, message = "some msg")
@Digits(integer = 3, fraction = 0, message = "some msg")
private int someField;

Dto is used in @RestController class as input method (@PostMapping) argument.

@Min and @Max works fine, but @Digits doesn't. When I send number, for instance 95.5, it is converted to 95 and any exception is thrown. Why it is not checked by @Digits?

like image 353
enyoucky Avatar asked Oct 28 '25 15:10

enyoucky


1 Answers

I was getting same issue, got resolved by using BigDecimal instead of BigInteger/Integer/int. As you have defined it as int it will auto remove decimal and then apply validation. Try using and datatype which has decimal part in it like BigDecimal. @Digit will work with BigDecimal.

like image 147
Arpit Tripathi Avatar answered Oct 30 '25 05:10

Arpit Tripathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!