Search code examples
javaannotationsbigdecimal

Check if bigdecimal has only 2 digits after precision using @javax.validation.constraints.Digits


I have a following class.

Class Item {

   private BigDecimal amount;

   ....
}

How I can validate amount that It should contain only two digits after precision. i.e

2.19 is correct

and

2.292 is incorrect

using annotation @javax.validation.constraints.Digits And how to show custom error message for this ?

Thank you :)


Solution

  • Give annotation to amount field of Item class as follows

    class Item {
    
       @Digits(integer = 6, fraction = 2, message = "{javax.validation.constraints.Digits.message}")
       private BigDecimal amount;
    }
    

    In the above class integer and fraction are compulsory and message is optional parameter to @Digit and there we can configure custom error message.

    Now, we create a properties file with name ValidationMessages.properties in source directory. It will look like something..

    javax.validation.constraints.Digits.message = "custom error message will be here"