在从记录的here学习BeanValidation时,我发现@Digits
支持String
数据类型。这里是文档的快照。
package javax.validation.constraints;
/**
* The annotated element must be a number within accepted range
* Supported types are:
* <ul>
* <li><code>BigDecimal</code></li>
* <li><code>BigInteger</code></li>
* <li><code>String</code></li>
* <li><code>byte</code>, <code>short</code>, <code>int</code>, <code>long</code>,
* and their respective wrapper types</li>
* </ul>
* <p/>
* <code>null</code> elements are considered valid
*
* @author Emmanuel Bernard
*/
Digits如何处理String类型?基于@Digit
验证String
类型的基础?它会像数字正则表达式验证(@Pattern)吗?
答案 0 :(得分:1)
JSR-303定义了一个接口,因此您应该检查实现的功能。如果使用Hibernate Validator,则在DigitsValidatorForCharSequence类中定义支持@Digit约束的String验证器(请注意String类实现CharSequence接口)。
该实现解析给定的String,如果它是有效的BigDecimal,则验证器返回true。
这是上述类中定义的isValid方法(以及用于解析值的私有方法):
public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) {
//null values are valid
if ( charSequence == null ) {
return true;
}
BigDecimal bigNum = getBigDecimalValue( charSequence );
if ( bigNum == null ) {
return false;
}
int integerPartLength = bigNum.precision() - bigNum.scale();
int fractionPartLength = bigNum.scale() < 0 ? 0 : bigNum.scale();
return ( maxIntegerLength >= integerPartLength && maxFractionLength >= fractionPartLength );
}
private BigDecimal getBigDecimalValue(CharSequence charSequence) {
BigDecimal bd;
try {
bd = new BigDecimal( charSequence.toString() );
}
catch ( NumberFormatException nfe ) {
return null;
}
return bd;
}