我试图在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;
}
验证问题:数值超出范围(<20位>。<0位>预期)
你已经将小数部分的位数限制为0
意味着没有允许的分数,即使你的0.0
中没有任何,但你应该确认是这种情况,我认为你有Double
值,即0 < x < 0.1
你可以也尝试使用Float
用于相同的字段,并检查是否有同样的问题?
字段或属性的值必须是指定范围内的数字。 integer元素指定数字的最大整数位数,fraction元素指定数字的最大小数位数。
或者,你可以尝试;
@DecimalMin("0.00")
@DecimalMax("99999999999999999.00")
我认为buildArea的主要问题是它的数据类型Double。
https://www.owasp.org/index.php/Bean_Validation_Cheat_Sheet
上面的链接说@Digits允许的数据类型不支持Double。
我不明白。如果你有小数部分的1位数,如0.0
,为什么你用@Digits
限制fraction=0
?该限制要确保您没有小数,因此在您的情况下只有整数有效。
这是有效的:
@Digits(integer=10, fraction=1)
private Double double1 = 0.0;
这也是有效的:
@Digits(integer=10, fraction=0)
private Integer integer1 = 0;
但这不是有效的:
@Digits(integer=10, fraction=0)
private Double double1 = 0.0; // Double not allowing a fraction part = integer, so you must change type here.