Application of Spring Validation Verification Framework in Practical Projects

Before introducing the Spring Validation validation framework, let's take a look at some of our commonly used validation annotations

limit Explain
@Null Restriction can only be null
@NotNull The restriction must not be null
@AssertFalse The restriction must be false
@AssertTrue The restriction must be true
@DecimalMax(value) The limit must be a number not greater than the specified value
@DecimalMin(value) The limit must be a number not less than the specified value
@Digits(integer,fraction) The limit must be a decimal number, and the number of integers must not exceed integer, and the number of decimal parts must not exceed fraction.
@Future Limitations must be a future date
@Max(value) The limit must be a number not greater than the specified value
@Min(value) The limit must be a number not less than the specified value
@Past Restrictions must be a past date
@Pattern(value) Restrictions must conform to specified regular expressions
@Size(max,min) Limited character length must be between min and max
@Past Verify that the element value (date type) of the annotation is earlier than the current time
@NotEmpty Verify that the element value of the annotation is not null and not empty (string length is not 0, set size is not 0)
@NotBlank Verify that the element value of the annotation is not empty (not null, the length after removing the first space is 0), unlike @NotEmpty, @NotBlank only applies to strings and removes the space of strings when comparing.
@Email Verify that the element value of the annotation is Email, or you can specify a custom email format through regular expressions and flag

After seeing this form, do you feel familiar with it? As long as it is interactive website data validation, it is an indispensable function.

How Spring Validation is used in conjunction with BindingResult
  • Create a Spring Book project and create the corresponding entity class.
@Data
class Employee {

    @NotNull(message = "name must be not empty.")
    private String name;

    @NotNull
    @Max(value = 35, message = "Must be less than 35.")
    private Integer age;

    @NotNull(message = "phone number must be not empty.")
    private String phone;

    @Email
    @NotNull(message = "e-mail wrong.")
    private String eMail;
}
@Data
public class Manager {

    @NotNull(message = "Id must be not empty.")
    private Integer id;

    @Valid
    @Size(min = 1, message = "At least one employee")
    private List<Employee> employees;
}
  • Create a controller for the test
@RestController
@RequestMapping("/user")
public class TestController {

    @PostMapping("/add")
    public String addUser(@RequestBody @Valid Manager manager, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<String> errorMessages = new ArrayList<>();
            for (ObjectError error : bindingResult.getAllErrors()) {
                errorMessages.add(error.getDefaultMessage());
                System.out.println(error.toString());
            }
            return "fail";
        }
        return "success";
    }
}
  • Test Verification Results
    • Prepare a test data as follows:
      { "id":10001, "employees":[ { "name":null, "age":40, "phone":"1111", "eMail":"dss" } ] }
    • Start testing, using postman
    • Result presentation
      You can see the verification results of name, age and email fields, but phone I randomly entered a series of numbers, which should be checked, but the Spring Validation verification framework does not provide annotations for mobile phone number verification, so the next custom verification will appear.
Custom Check

Business requirements are always more complex than the simple checks provided by the framework, and we can customize the checks to meet our needs. Customizing Spring Validation is very simple and consists of two steps.

  • Define an annotation
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PhoneValidator.class)
public @interface Phone {
    /**
     * Messages that fail to verify
     */
    String message() default "Please enter the correct cell phone number.";

    /**
     * Group Check
     */
    Class<?>[] groups() default {};


    Class<? extends Payload>[] payload() default {};
}
  • Implementing this annotation
public class PhoneValidator implements ConstraintValidator<Phone, String> {
    @Override
    public boolean isValid(String phone, ConstraintValidatorContext constraintValidatorContext) {
        if(!StringUtils.isEmpty(phone)){
            String regex = "^1(3|4|5|7|8)\\d{9}$";
            return phone.matches(regex);
        }
        return true;
    }
}
  • test

    You can see that the format checking of mobile phone number has also been successful, which proves that the custom annotation of the framework is successful.
@ A simple comparison between Validated and @Valid

@ Valid annotations are mostly similar to @Validated annotations; the main differences between the two are:

  • @ Valid belongs to javax, while @Validated belongs to spring.
  • @ Valid supports nested validation (the example above uses nested validation), while @Validated does not.
  • @ Validated supports grouping, while @Valid does not.

Tags: Spring less Mobile

Posted on Thu, 29 Aug 2019 00:10:41 -0700 by bogdan