优雅校验参数之@NotNull、@NotEmpty、@NotBlank

优雅校验参数之@NotNull、@NotEmpty、@NotBlank

首先说明三个注解的区别:

注解 作用 数据类型(一般情况下)
@NotNull 不能为null,可以为empty(也就是可以为"") Integer、Long、BigDecimal、Date
(可以使用@size、@Max、@Min、@Range对Integer进行限制)
@NotEmpty 不能为null,且长度必须大于0 集合、数组
@NotBlank 不为null,只作用于String上,且调用trim()后长度必须大于0,即必须有实际的字符 String(可以使用@Length对长度进行限制)

用法:

  1. 实体类的属性值上写上对应的参数校验注解

    public class UserRegisterDto implements Serializable {
          
          
        @NotBlank(message = "电话号码不可为空")
        @Schema(description = "电话号码", required = true)
        private String phone;
    
        @NotNull(message = "登录渠道不可为空")
        @Schema(description = "登录渠道", required = true)
        private Integer channel;
    }
    
  2. 对应的controller上添加@@Valid注解

    public class UserRegisterController {
          
          
    
        @PostMapping("/register")
        @Operation(summary = "c端用户注册接口", description = "c端注册")
        public HttpResult<UserInfo> register(@RequestBody @Valid UserRegisterDto dto) {
          
          
    		// TODO do something
            return HttpResult.success(userInfo);
        }
    
    }
    

**注意:**如果对应的类型写错了会报一下的错误。我这边是在channel字段上(Integer类型)上写了@NotEmpty,导致了下面的报错。改成@NotNull就没问题啦

HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.Integer'. Check configuration for 'channel'

猜你喜欢

转载自blog.csdn.net/weixin_45340300/article/details/130890384