Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 985
Prashant Shilimkar Avatar asked Jun 11 '14 10:06

Prashant Shilimkar


2 Answers

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"
like image 138
Prashant Shilimkar Avatar answered Oct 01 '22 16:10

Prashant Shilimkar


Try putting a constraint on @Digits:

@Digits(integer = 6, fraction = 2)
public String getAmount() {
   return amount;
}
like image 6
Arash Saidi Avatar answered Oct 02 '22 16:10

Arash Saidi