springBoot验证注解
引入maven:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> </dependencies>
写法:
@Data public class User { private String id; @NotBlank(message = "用户名不能为空") private String username; @NotBlank(message = "密码不能为空") private String password; @Email(message = "Email格式错误") private String email; @PastOrPresent(message = "日期小于等于当前时间") private Date birthday; @Pattern(regexp = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$" , message = "手机号格式错误") private String phone; @Min(value = 0, message = "年龄超出范围,最小值为0") @Max(value = 120, message = "年龄超出范围,最大值为120") private Integer age; }
验证注解:
注解 | 描述 |
@AssertFalse | 所注解的元素必须是Boolean类型,且值为false |
@AssertTrue | 所注解的元素必须是Boolean类型,且值为true |
@DecimalMax | 所注解的元素必须是数字,且值小于等于给定的值 |
@DecimalMin | 所注解的元素必须是数字,且值大于等于给定的值 |
@Digits | 所注解的元素必须是数字,且值必须是指定的位数 |
@Future | 所注解的元素必须是将来某个日期 |
@Max | 所注解的元素必须是数字,且值小于等于给定的值 |
@Min | 所注解的元素必须是数字,且值小于等于给定的值 |
@Range | 所注解的元素需在指定范围区间内 |
@NotNull | 所注解的元素值不能为null |
@NotBlank | 所注解的元素值有内容 |
@Null | 所注解的元素值为null |
@Past | 所注解的元素必须是某个过去的日期 |
@PastOrPresent | 所注解的元素必须是过去某个或现在日期 |
@Pattern | 所注解的元素必须满足给定的正则表达式 |
@Size | 所注解的元素必须是String、集合或数组,且长度大小需保证在给定范围之内 |
所注解的元素需满足Email格式 |
注意⚠️:
1.其中 ,username与password属性必传而其他属性没有限制
2.注解中的message属性会在校验失败抛出异常时赋给defaultMessage属性
注意⚠️:
须在controller层填写注解@Valid,不然不会运行以上注解
Controller层:
@GetMapping("/register") //@Valid在下一行 public R register(@Valid UserInfo req){ R r = new R(); r.setData(userService.register(req)); return r; }
Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 26
Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 27
Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 28