@valid用来验证对象是否符合要求
一、添加依赖
我一开始用时发现该注解没发挥作用,发现springboot需要在pom文件里添加他的依赖,看网上以前似乎不用,可能后来改了。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
二、使用
首先需要说明的是postmapping注解下,方法是可以传递整个对象的,而不是仅仅几个参数。如下端代码
public Luckymoney create(@RequestParam("producer") String producer,
@RequestParam("money") BigDecimal money) {
Luckymoney luckymoney = new Luckymoney();
luckymoney.setProducer(producer);
luckymoney.setMoney(money);
return repository.save(luckymoney);
里面的@RequestParam("producer") String producer@RequestParam("money") BigDecimal money可以直接被
Luckymoney money取代,注意传整个对象时,似乎要该对象上所有的属性的值都要传上去,否则数据库不会保存,也不会报错提示你
因为要验证对象Luckymoney,先实体类里面设置上条件
@Min(value = 18,message = "数值太小")
private Integer money;
@PostMapping("/luckymoneys")//
public Luckymoney create(@Valid Luckymoney money , BindingResult bindingResult){
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return null;
}
money.setMoney(money.getMoney());
money.setProducer(money.getProducer());
return repository.save(money);
}
BindingResult存储验证结果
最后在后台显示
valid的相关注解
@Null 限制只能为null
@NotNull 限制必须不为null
@AssertFalse 限制必须为false
@AssertTrue 限制必须为true
@DecimalMax(value) 限制必须为一个不大于指定值的数字
@DecimalMin(value) 限制必须为一个不小于指定值的数字
@Digits(integer,fraction) 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
@Future 限制必须是一个将来的日期
@Max(value) 限制必须为一个不大于指定值的数字
@Min(value) 限制必须为一个不小于指定值的数字
@Past 限制必须是一个过去的日期
@Pattern(value) 限制必须符合指定的正则表达式
@Size(max,min) 限制字符长度必须在min到max之间
@Past 验证注解的元素值(日期类型)比当前时间早
@NotEmpty 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@NotBlank 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
@Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式需要注意每个注解对应的数据类型