The difference between @Valid and @Validated and detailed use and parameter annotation verification

1. The difference between @Validated and @Valid

You must add this annotation to the controller, otherwise the verification annotation will not take effect

group

@Validated: Provides a grouping function, which can adopt different verification mechanisms according to different groups when entering parameter verification. When no grouping attribute is added, the default verification has no grouping verification attribute. @Valid: As a standard JSR-303 specification,
also There is no function of absorbing groups

Location

@Validated: Can be used on types, methods and method parameters. But it cannot be used on member properties (fields). If @Validated is annotated on member properties, it will report that it is not applicable to field errors.
@Valid: can be used on methods, constructors, method parameters and member properties (fields), both Whether the latter can be used on member attributes (fields) directly affects whether nested validation functions can be provided

在接口使用注解进行校验,在类上添加注解:@Validated

nested validation

@Validated: When used on method input parameters, it cannot provide nested validation function alone, and cannot be used on member attributes (fields), nor can it prompt the framework to perform nested validation. It can cooperate with the nested validation annotation @Valid to perform nested validation.
@Valid: When used on method input parameters, it cannot provide nested validation function alone, but can be used on member attributes (fields), prompting the validation framework to perform nested validation, and can cooperate with the nested validation annotation @Valid to perform nested validation

1. Example of grouping

Define grouping interface

public interface IGroupA {
    
    
}

public interface IGroupB {
    
    
}

Define the validation parameter Bean

public class StudentBean{
    
    
   //只在分组为IGroupB的情况下进行验证
   @Min(value = 18, message = "年龄不能小于18岁", groups = {
    
    IGroupB.class})
}

controller layer

@RestController
public class CheckController {
    
    
    @PostMapping("stuA")
    public String addStuA(@Validated({
    
    IGroupA.class}) @RequestBody StudentBean studentBean){
    
    
        return "add studentA success";
    }
    
    @PostMapping("stuB")
    public String addStuB(@Validated({
    
    IGroupB.class}) @RequestBody StudentBean studentBean){
    
    
        return "add studentB success";
    }
}
同时调用两个方法,传入参数为age=15
addStuA方法结果为:age:15 add studentA success
addStuA方法结果为:age:年龄不能小于18

Notice!

When groups are not assigned, verification is required each time.
When multiple verification methods are required for a parameter, different groups can be assigned

2. Group sequence

By default, different levels of constraint verification are unordered, but in some cases, order verification is very important. A
group can be defined as a sequence of other groups, and it must conform to the order specified by the sequence when using it for verification
. During group sequence verification, if the verification of the group at the front of the sequence fails, the subsequent group will no longer be verified

Example: Defining a Group Sequence

@GroupSequence({
    
    Default.class, IGroupA.class, IGroupB.class})
public interface IGroup {
    
    
}

For the beans that need to be verified, respectively define IGroupA to verify age, and IGroupB to verify email:

public class StudentBean implements Serializable {
    
    

   @NotBlank(message = "用户名不能为空")
   private String name;

   //只在分组为IGroupB的情况下进行验证
   @Min(value = 18, message = "年龄不能小于18岁", groups = {
    
    IGroupA.class})
   private Integer age;

   @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式错误")
   private String phoneNum;

   @Email(message = "邮箱格式错误", groups = {
    
    IGroupB.class})
   private String email;
}

Test code:

@RestController
public class CheckController {
    
    
   @PostMapping("stu")
   public String addStu(@RequestBody @Validated({
    
    IGroup.class}) StudentBean studentBean){
    
    
      return "add student success";
   }
}

Test result: Only the errors defined by IGroupA are checked, but IGroupB is not checked

3. Nested validation

A pojo class to be validated, which also contains the object to be validated. It is necessary to annotate @Valid on the object to be validated to verify the member attributes in the object to be validated. @Validated cannot be used here

Example: Bean for Constraint Validation

public class TeacherBean {
    
    
   @NotEmpty(message = "老师姓名不能为空")
   private String teacherName;
   @Min(value = 1, message = "学科类型从1开始计算")
   private int type;
}

public class StudentBean implements Serializable {
    
    

   @NotBlank(message = "用户名不能为空")
   private String name;

   //只在分组为IGroupB的情况下进行验证
   @Min(value = 18, message = "年龄不能小于18岁", groups = {
    
    IGroupA.class})
   private Integer age;

   @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式错误")
   private String phoneNum;

   @Email(message = "邮箱格式错误", groups = {
    
    IGroupB.class})
   private String email;

   @NotNull(message = "任课老师不能为空")
   @Size(min = 1, message = "至少有一个老师")
   private List<TeacherBean> teacherBeanList;
}

Note: Here, only NotNull, and Size are checked for teacherBeans, and the fields in the teacher information are not checked. The
type in the teacher does not meet the constraint requirements, but it can pass the test because it is not done in the student. Nested validation.
You can add @Valid to teacherBeans

@Valid
@NotNull(message = "任课老师不能为空")
@Size(min = 1, message = "至少有一个老师")
private List<TeacherBean> teacherBeanList;

In this case, the parameters in the TeacherBean are verified

2. Verification Notes

//适用于基本数据类型(Integer,Long,Double等等),当 @Null,@NotNull 注解被使用在 String 类型的数据上,则表示该数据(不)能为 Null(但是可以为 Empty)
//必须为null
@Null
//不能为null
@NotNull

//只能作用在String上,不能为null,而且调用trim()后,长度必须大于0
@NotBlank
//适用于 String、Collection集合、Map、数组等等,不能为null,并且长度必须大于0
@NotEmpty

//用于boolean字段,必须为true
@AssertTrue
//用于boolean字段,必须为false
@AssertFalse

//必须为数字,其最小值必须大于等于指定的值
@Min(value)  eg: @Min(100) or @Min(value = 100, message = "最小值为100")
//必须为数字,其最大值必须小于等于指定的值
@Max(value)

//支持Decimal, 只能大于或等于该值
@DecimalMin(value)
//支持Decimal, 只能小于或等于该值
@DecimalMax(value)

//数字必须在范围内
@Range  eg:@Range(min =1 ,max = 100, message = "范围为1-100")
//大小必须在范围内
@Size eg:@Size(min=5, max=10, message="字符串或数组的长度必须在5-10之间")

//校验小数,小数点前支持多少位,小数点后支持多少位
@Digits(integer=6,fraction=2, message="小数点前支持6位,小数点后支持2位")

//必须是一个过去的日期
@Past
//必须是一个将来的日期
@Future

//必须符合指定的正则表达式
@Pattern(value)

//必须是电子邮件地址
@Email

//字符创长度必须在规定范围内,只能用于字符串
@Length(min=,max=)

//字符串非空
@NotEmpty

//对信用卡号进行一个大致的验证
@CreditCardNumber

//检查是否是一个有效的URL,如果提供了protocol,host等,则该URL还需满足提供的条件
@URL(protocol=,host,port)

Guess you like

Origin blog.csdn.net/weixin_45265547/article/details/126296607