Spring Boot 使用validation通过注解实现数据校验

一、依赖

		<!--https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>

二、实体类

	@TableField("username")
    @NotBlank(message = "{user.name.notBlank}")
    private String username;
    @NotBlank(message = "{user.password.notBlank}")
    @TableField("password")
    private String password;
    @NotBlank(message = "{user.email.notBlank}")
    @Email(message = "{user.email.pattern}")
    @TableField("email")
    private String email;

三、配置

查看LocalValidationFactoryBean类的源码,发现Spring Boot默认的ValidationMessagesSource校验出错时的提示文件是在resources文件夹下文件ValidationMessages.properties

ValidationMessages.properties

user.name.notBlank=用户名不能为空
user.password.notBlank=密码不能为空
user.email.notBlank=邮箱不能为空
user.email.pattern=邮箱格式不正确

ValidationMessages.properties

四、Controller

/**
     * 添加用户
     *
     * @param user 用户对象
     * @return
     */
    @PostMapping("/insert")
    public ResultVO<Object> insert(@Validated @RequestBody User user, BindingResult bindingResult) {
    
    
        if (bindingResult.hasErrors()) {
    
    
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            return ResultVOUtil.fail(allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList()));
        }
        userService.insert(user.doBuild());
        return ResultVOUtil.success();
    }

五、效果

效果

六、参考注解

注解 作用
@NotNull 值不能为空
@Null 值必须为空
@Pattern(regex=) 字符串必须匹配正则表达式
@Size(min, max) 集合元素的数量必须在min和max之间
@CreditCardNumber(ignoreNonDigitCharacters=) 字符串必须是信用卡号,按照美国的标准验证
@Email 字符串必须是Email地址
@Length(min, max) 检查字符串的长度
@NotBlank 字符串不能为空串
@NotEmpty 字符串不能为null, 集合必须有元素
@Range(min, max) 数字必须大于min, 小于max
@SafeHtml 字符串必须是安全的html
@URL 字符串必须是合法的URL
@AssertFalse 值必须是false
@AssertTrue 值必须是true
@DecimalMax(value=, inclusive=) 值必须小于等于(inclusive=true)/小于(inclusive=false)属性指定的值,也可以注释在字符串类型的属性上。
@DecimalMin(value=, inclusive=) 值必须大于等于(inclusive=true)/小于(inclusive=false)属性指定的值,也可以注释在字符串类型的属性上。
@Digist(integer=,fraction=) 数字格式检查。integer指定整数部分的最大长度,fraction指定小数部分的最大长度
@Future 时间必须是未来的
@Past 事件必须是过去的
@Max(value=) 值必须小于等于value指定的值。不能注解在字符串类型属性上。
@Min(value=) 值必须小于等于value指定的值。不能注解在字符串类型属性上

点赞转发关注,你的支持是我最大的动力!

猜你喜欢

转载自blog.csdn.net/y1534414425/article/details/108878678