使用@javax.validation.constraints.Digits 检查 bigdecimal 在精度后是否只有 2 位数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24160064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if bigdecimal has only 2 digits after precision using @javax.validation.constraints.Digits
提问by Prashant Shilimkar
I have a following class.
我有以下课程。
Class Item {
private BigDecimal amount;
....
}
How I can validate amountthat It should contain only two digits after precision. i.e
我如何可以验证量,它应该精度后只包含两个数字。IE
2.19 is correct
2.19 是正确的
and
和
2.292 is incorrect
2.292 不正确
using annotation @javax.validation.constraints.Digits
And how to show custom error message for this ?
使用注释@javax.validation.constraints.Digits
以及如何为此显示自定义错误消息?
Thank you :)
谢谢 :)
采纳答案by Prashant Shilimkar
Give annotation to amount
field of Item
class as follows
amount
对Item
类的字段进行注释如下
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.
在上面的类中,integer
并且fraction
是强制性的,消息是可选参数,@Digit
我们可以在那里配置自定义错误消息。
Now, we create a properties file with name ValidationMessages.propertiesin source directory. It will look like something..
现在,我们在源目录中创建一个名为ValidationMessages.properties的属性文件。它看起来像什么..
javax.validation.constraints.Digits.message = "custom error message will be here"
回答by Arash Saidi
Try putting a constraint on @Digits
:
尝试对 施加约束@Digits
:
@Digits(integer = 6, fraction = 2)
public String getAmount() {
return amount;
}