校验注解
使用方法:
- **在需要进行校验的实体前加上 **
@Valid
- 在需要进行校验的字段上进行对应校验
常用校验有:
@AssertTrue / @AssertFalse
验证适用字段:boolean
注解说明:验证值是否为true / false
@DecimalMax / @DecimalMin
验证适用字段:BigDecimal,BigInteger,String,byte,short,int,long
注解说明:验证值是否小于或者等于指定的小数值,要注意小数存在精度问题
@Digits
验证适用字段:BigDecimal,BigInteger,String,byte,short,int,long
注解说明:验证值的数字构成是否合法
属性说明:integer:指定整数部分的数字的位数。fraction: 指定小数部分的数字的位数。
@Future / @Past
验证适用字段:Date,Calendar
注解说明:验证值是否在当前时间之后 / 之前
属性说明:公共
@Max / @Min
验证适用字段:BigDecimal,BigInteger,String,byte,short,int,long
注解说明:验证值是否小于或者等于指定的整数值
属性说明:公共
注意事项:建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单提交的值为“”时无法转换为int
@NotNull / @Null
验证适用字段:引用数据类型
注解说明:验证值是否为非空 / 空
属性说明:公共
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为Null或者是EMPTY.
@NotBlank 与 @NotEmpty 的区别:空格(" ")对于 NotEmpty 是合法的,而 NotBlank 会抛出校验异常
@Pattern
验证适用字段:String
注解说明:验证值是否配备正则表达式
属性说明:regexp:正则表达式flags: 指定Pattern.Flag 的数组,表示正则表达式的相关选项。
@Size
验证适用字段:String,Collection,Map,数组
注解说明:验证值是否满足长度要求
属性说明:max:指定最大长度,min:指定最小长度。
@Length(min=, max=):专门应用于String类型
@Valid
验证适用字段:递归的对关联对象进行校验
注解说明:如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验(是否进行递归验证)
属性说明:无
@Range(min=, max=) 被指定的元素必须在合适的范围内
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@URL(protocol=,host=, port=,regexp=, flags=)
分组校验的实现
**这里就必须区分 **@Valid
与 @Validated
二者区别:
@Valid
所属包为:javax.validation.Valid
@Validated
所属包为:org.springframework.validation.annotation.Validated
@Validated
是 @Valid
的一次封装,是Spring提供的校验机制使用。@Valid
不提供分组功能
-
若需使用分组功能,首先需对实体中需要进行的特殊校验字段进行分组如下:
public class Attachment { @NotBlank(message = "id can not be blank!", groups = {All.class, Update.class}) private String id; @NotBlank(message = "fileName can not be blank!", groups = {All.class}) private String fileName; @NotBlank(message = "filePath can not be blank!", groups = {All.class}) private String filePath; @NotBlank(message = "metaData can not be empty!", groups = {All.class}) private String metaData; @NotBlank(message = "uploadTime can not be blank!", groups = {All.class}) private String uploadTime; public Attachment(@NotBlank(message = "id can not be blank!", groups = {All.class, Update.class}) String id) { this.id = id; } @NotBlank(message = "uploadTime can not be blank!") private String filed; public interface All { } public interface Update { } }
对该实体字段分为:All,Update,(若未设置分组的则默认未default)
-
在对应controller指定注解分类(不指定则为default)
@GetMapping("validate") public BaseMerchant validateDemo(@Validated(value = {Attachment.All.class}) Attachment attachment) { return null; }