Spring Boot uses validation to implement data verification through annotations

1. Dependence

		<!--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>

Two, entity class

	@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;

Three, configuration

Looking LocalValidationFactoryBeanat the source code of the class, it is found that the default ValidationMessagesSourceprompt file for Spring Boot's verification error is the file in the resourcesfolderValidationMessages.properties

ValidationMessages.properties

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

ValidationMessages.properties

Four, 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();
    }

Five, effect

effect

Six, reference notes

annotation effect
@NotNull Value cannot be empty
@Null Value must be empty
@Pattern(regex=) String must match regular expression
@Size(min, max) The number of collection elements must be between min and max
@CreditCardNumber(ignoreNonDigitCharacters=) The string must be a credit card number, verified according to US standards
@Email The string must be an email address
@Length(min, max) Check the length of the string
@NotBlank The string cannot be an empty string
@NotEmpty The string cannot be null, the collection must have elements
@Range(min, max) Number must be greater than min, less than max
@SafeHtml The string must be safe html
@URL The string must be a valid URL
@AssertFalse Value must be false
@AssertTrue Value must be true
@DecimalMax(value=, inclusive=) The value must be less than or equal to (inclusive=true)/less than (inclusive=false) the value specified by the attribute, and it can also be annotated on the string type attribute.
@DecimalMin(value=, inclusive=) The value must be greater than or equal to (inclusive=true)/less than (inclusive=false) the value specified by the attribute, and it can also be annotated on a string type attribute.
@Digist(integer=,fraction=) Number format check. integer specifies the maximum length of the integer part, fraction specifies the maximum length of the fractional part
@Future Time must be in the future
@Past Event must be past
@Max(value=) The value must be less than or equal to the value specified by value. Cannot be annotated on string type attributes.
@Min(value=) The value must be less than or equal to the value specified by value. Cannot be annotated on string type attributes

Like, forward and follow, your support is my biggest motivation!

Guess you like

Origin blog.csdn.net/y1534414425/article/details/108878678