我正在尝试使用Hibernate验证API验证Double
字段 - 使用@Digits
注释
<areaLength>0</areaLength>
<buildArea>0.0</buildArea>
@Digits(integer=10, fraction=0)
private Long areaLength = null; // Here areaLength = 0
@Digits(integer=20, fraction=0)
private Double buildArea = null; // Here buildArea = 0.0
此处areaLength
没有违反约束,
但是buildArea
违反了约束,说
buildArea numeric value out of bounds (<20 digits>.<0 digits> expected)
10.0没有违规,但违反了0.0。
有人知道原因吗?
完整代码:
public class ValidationTest {
public static void main(String a[]) {
Vehicle vehBean = new Vehicle();
try {
if (vehBean != null) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Vehicle>> violations = validator.validate(vehBean);
if (violations!= null && violations.size() > 0) {
for (ConstraintViolation<Vehicle> violation : violations) {
System.out.println("Validation problem : " + violation.getMessage());
}
}
}
} catch(Exception e) {
throw e;
}
}
}
class Vehicle {
@Digits(integer=20, fraction=0)
private Double buildArea = 0.0;
}
验证问题:数值超出界限(&lt; 20位&gt;。&lt; 0位&gt;预期)
答案 0 :(得分:3)
您已将小数部分的位数限制为0
,这意味着不允许分数,即使您的0.0
中没有任何分数,但您应该确认是这种情况,我认为您的Double
值为0 < x < 0.1
您还可以尝试将Float
用于同一字段,并检查是否存在同样的问题?
字段或属性的值必须是指定范围内的数字。 integer数字指定数字的最大整数位数,fraction元素指定数字的最大小数位数。
答案 1 :(得分:2)
或者,您可以尝试;
@DecimalMin("0.00")
@DecimalMax("99999999999999999.00")
答案 2 :(得分:0)
我认为buildArea的主要问题是其数据类型Double。
https://www.owasp.org/index.php/Bean_Validation_Cheat_Sheet
上面的链接说@Digits允许的数据类型不支持Double。
答案 3 :(得分:0)
I don't get it. If you have 1 digits in fraction part, like 0.0
, why do you restrict in @Digits
with fraction=0
? That restriction wants to ensure that you have no decimals, so only integers are valid in your case.
This is valid:
@Digits(integer=10, fraction=1)
private Double double1 = 0.0;
This is valid, too:
@Digits(integer=10, fraction=0)
private Integer integer1 = 0;
But this is not valid:
@Digits(integer=10, fraction=0)
private Double double1 = 0.0; // Double not allowing a fraction part = integer, so you must change type here.