java validation
javax的校验机制是基于标准JSR-303规范()。
hibernate是扩展了javax的接口
1. 常用注解
注解 | 类型 | 使用说明 | 注意事项 |
---|---|---|---|
@Null | 任何类型 | 对象必须为null | |
@NotNull | 任何类型 | 对象不能为null | |
@NotBlank | String | 对象不能为null,并且trim后length>0 | |
@NotEmpty | String、Collection、Map、Array | 对象不能为null或为空 | |
@AssertFalse | boolean | 对象为false | null被视为有效 |
@AssertTrue | boolean | 对象为true | null被视为有效 |
@Size | String、Collection、Map、Array | 对象的size必须在指定的范围内(闭区间) | null被视为有效 |
@Max | BigDecimal、BigInteger、byte、short、int、long | 对象必须为数字,其值必须小于等于指定值 | null被视为有效 |
@Min | BigDecimal、BigInteger、byte、short、int、long | 对象必须为数字,其值必须大于等于指定值 | null被视为有效 |
@DecimalMax | BigDecimal、BigInteger、CharSequence、byte、short、int、long | 对象必须为数字,其值必须小于等于指定值 | null被视为有效 |
@DecimalMin | BigDecimal、BigInteger、CharSequence、byte、short、int、long | 对象必须为数字,其值必须大于等于指定值 | null被视为有效 |
@Digits | BigDecimal、BigInteger、CharSequence、byte、short、int、long | 验证对象整数位和小数位的上限 | null被视为有效 |
@Positive | BigDecimal、BigInteger、byte、short、int、long、float、double | 对象必须为正数 | null被视为有效 |
@PositiveOrZero | BigDecimal、BigInteger、byte、short、int、long、float、double | 对象必须为正数或者是0 | null被视为有效 |
@Negative | BigDecimal、BigInteger、byte、short、int、long、float、double | 对象必须为负数 | null被视为有效 |
@NegativeOrZero | BigDecimal、BigInteger、byte、short、int、long、float、double | 对象必须为负数或者是0 | null被视为有效 |
@Past | 对象必须是过去的一个时间 | null被视为有效 | |
@PastOrPresent | 对象必须是过去或现在的一个时间 | null被视为有效 | |
@Future | 对象必须是将来的一个时间 | null被视为有效 | |
@FutureOrPresent | 对象必须是将来或现在的一个时间 | null被视为有效 | |
CharSequence | 对象必须为email格式 | null被视为有效 | |
@Pattern | CharSequence | 对象匹配指定的正则表达式 | null被视为有效 |
2. 原理
通过切面( MethodValidationPostProcessor.)来扫描所有的@Valid注解org.springframework.validation.beanvalidation.MethodValidationPostProcessor
3. 自定义扩展
1 |
|
1 |
|
java validation
https://www.wekri.com/java/javax-validation/