2

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?

enyoucky
  • 103
  • 1
  • 9
  • 1
    I guess in this case the values are assigned on a first step to "somefield" and in a later stage those values are validated. 95 is a two digit value and it is what the validation engine sees at the moment of validation. Maybe the problem is to check why such convertion was allowed, i mean, from 95.5 to 95. – Juan BC Dec 29 '20 at 10:46

2 Answers2

2

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.

0

Type of "someField" is int, so when you pass value 95.5 it get casted to int by ignoring fractional part. If you change type of someField to wrapper type like BigDecimal,BigInteger etc. then it should work as expected.

Deepak Muthekar
  • 391
  • 2
  • 6