常用注解
空与非空检查
| 注解 | 支持 Java 类型 | 说明 |
|---|---|---|
| @Null | Object | 为 null |
| @NotNull | Object | 不为 null |
| @NotBlank | CharSequence | 不为 null,且必须有一个非空格字符 |
| @NotEmpty | CharSequence、Collection、Map、Array | 不为 null,且不为空(length/size>0) |
Boolean 值检查
| 注解 | 支持 Java 类型 | 说明 | 备注 |
|---|---|---|---|
| @AssertTrue | boolean、Boolean | 为 true | 为 null 有效 |
| @AssertFalse | boolean、Boolean | 为 false | 为 null 有效 |
日期检查
| 注解 | 支持 Java 类型 | 说明 | 备注 |
|---|---|---|---|
| @Future | Date、Calendar、Instant、LocalDate、LocalDateTime、LocalTime、MonthDay、OffsetDateTime、OffsetTime、Year、YearMonth、ZonedDateTime、HijrahDate、JapaneseDate、MinguoDate、ThaiBuddhistDate | 验证日期为当前时间之后 | 为 null 有效 |
| @FutureOrPresent | Date、Calendar、Instant、LocalDate、LocalDateTime、LocalTime、MonthDay、OffsetDateTime、OffsetTime、Year、YearMonth、ZonedDateTime、HijrahDate、JapaneseDate、MinguoDate、ThaiBuddhistDate | 验证日期为当前时间或之后 | 为 null 有效 |
| @Past | Date、Calendar、Instant、LocalDate、LocalDateTime、LocalTime、MonthDay、OffsetDateTime、OffsetTime、Year、YearMonth、ZonedDateTime、HijrahDate、JapaneseDate、MinguoDate、ThaiBuddhistDate | 验证日期为当前时间之前 | 为 null 有效 |
| @PastOrPresent | Date、Calendar、Instant、LocalDate、LocalDateTime、LocalTime、MonthDay、OffsetDateTime、OffsetTime、Year、YearMonth、ZonedDateTime、HijrahDate、JapaneseDate、MinguoDate、ThaiBuddhistDate | 验证日期为当前时间或之前 | 为 null 有效 |
数值检查
| 注解 | 支持 Java 类型 | 说明 | 备注 |
|---|---|---|---|
| @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 有效 |
| @Negative | BigDecimal、BigInteger,byte、short、int、long、float、double 以及包装类 | 负数 | 为 null 有效,0 无效 |
| @NegativeOrZero | BigDecimal、BigInteger,byte、short、int、long、float、double 以及包装类 | 负数或零 | 为 null 有效 |
| @Positive | BigDecimal、BigInteger,byte、short、int、long、float、double 以及包装类 | 正数 | 为 null 有效,0 无效 |
| @PositiveOrZero | BigDecimal、BigInteger,byte、short、int、long、float、double 以及包装类 | 正数或零 | 为 null 有效 |
| @Digits(integer = 3, fraction = 2) | BigDecimal、BigInteger、CharSequence,byte、short、int、long 以及包装类 | 整数位数和小数位数上限 | 为 null 有效 |
其他
| 注解 | 支持 Java 类型 | 说明 | 备注 |
|---|---|---|---|
| @Pattern | CharSequence | 匹配指定的正则表达式 | 为 null 有效 |
| CharSequence | 邮箱地址 | 为 null 有效,默认正则 `'.*'` | |
| @Size | CharSequence、Collection、Map、Array | 大小范围(length/size>0) | 为 null 有效 |
hibernate-validator 扩展约束(部分)
| 注解 | 支持 Java 类型 | 说明 |
|---|---|---|
| @Length | String | 字符串长度范围 |
| @Range | 数值类型和 String | 指定范围 |
| @URL | URL 地址验证 |
参考:
springboot 2.x 校验www.jianshu.com/p/5949ebcf2…
hibernate校验最佳实践 www.cnblogs.com/vcmq/p/1254…
自定义校验blog.csdn.net/calm_encode…
springmvc校验 blog.csdn.net/xu191665942…
参数校验进阶:blog.csdn.net/jinjiankang…
struts2 校验:blog.csdn.net/SuperstarSt…