java 在 Spring 中使用双值验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35460884/
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
validation with double value in Spring
提问by Ducthien
I want to check score which have value: 0.00 <= value<= 10.00
I used:
-Model(Score):
我想检查有值的分数:0.00 <= value<= 10.00
我用过:
-Model(Score):
@Range(min = (long) 0.0, max = (long) 10.0)
private double score;
-messages.properties:
-messages.properties:
Range.score.score=Please input 0<= score <=10
-servlet-context.xml:
-servlet-context.xml:
<beans:bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="messages" />
</beans:bean>
But the value = 10.01 has passed the check.
Please help me.
但 value = 10.01 已通过检查。
请帮我。
回答by Ducthien
I resolve my proplem with:
我解决了我的问题:
@DecimalMax("10.0") @DecimalMin("0.0")
private double score;
Thank you lots @ Kayaman ,@hyness
非常感谢@Kayaman,@hyness
回答by hyness
There are two problems. First problem is you are trying to specify a data type in the attribute of the annotation. You don't need to specify the data type or fraction either, this annotation only takes whole numbers.
有两个问题。第一个问题是您试图在注释的属性中指定数据类型。您也不需要指定数据类型或分数,此注释只需要整数。
Also, as specified by many others, doubles and floats are not allowed to rounding errors, so you need to use a BigDecimal instead of a double. BigDecimal has a doubleValue() method to get the value as a double.
此外,正如许多其他人所指定的,双精度数和浮点数不允许舍入错误,因此您需要使用 BigDecimal 而不是双精度数。BigDecimal 有一个 doubleValue() 方法来获取双精度值。
@Range(min = 0, max = 10)
private BigDecimal score;