“This is the 25th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

First, the verification framework

Validation framework is a framework used to validate data. This article will demonstrate how to validate data using existing constraint annotations and how to customize constraint annotations, and understand the principles of the JSR specification

Verify the model

The first is hierarchical validation which is validation at each level of the MVC architecture, which results in a lot of duplicate code

The second is Java Bean validation, which only binds the validation logic to the domain model with annotations, separating the validation logic from the business code

Bean Validation

Bean Validation is the metadata model and API that validates the response defined for Java beans

The JCP and JSR

The Java Community Process (JCP), established in 1998, is a formal Process that involves interested parties in defining the characteristics and future versions of Java beans

The JCP uses the JSR (Java Specification Requests) as a formal Specification document that describes the specifications and technologies proposed to be added to the Java architecture

  • JSR303 is Bean Validation 1.0
  • JSR349 is Bean Validation 1.1
  • JSR380 is Bean Validation 2.0

Bean Validation and Hibernate Validator

  • Hibernate Validator 4.3.1 Final
  • Hibernate Validator 5.1.1 Final
  • Hibernate Validator 6.0.1 Final

Plus: Hibernate Validator has nothing to do with Hibernate, the ORM framework

Hibernate Validator VS Spring Validation

Spring Validation encapsulates it twice on the basis of Hibernate Validator, making it easier and more efficient to validate data in Spring

Common constraint annotations

  • Null validation classes: @null, @notnull, @notempty, @notBlank
  • Scope check classes: @min, @size, @digits, @Future, @negative
  • Other verification classes: @email, @URL, @Assertture, and @pattern

Plus: @notempty will remove the left and right whitespace, @notblank will determine directly

Ii. Engineering construction

To create a New Maven project, select Maven-archetype-QuickStart

Import validation-related dependencies

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1. The Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.16. The Final</version>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>javax.el</artifactId>
    <version>2.2.6</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.18</version>
    <scope>provided</scope>
</dependency>
Copy the code

Add the Entity package and add the UserInfo entity class under the Entity package. Do not define any attributes at first, and then define attributes when authentication is required

@Data
public class UserInfo {

    private Integer userId;
    private String userName;
    private String passWord;
    private String email;
    private String phone;
    private Integer age;
    private Date birthday;
    private List<UserInfo> friends;

}
Copy the code

Use of primary constraint annotations

  • A null value validation
  • Scope of validation
  • Other validation

@NotNull

Add the @notnull annotation to the userId attribute of the UserInfo entity class (message=” userId cannot be empty “), where message is an authentication message and returns a message if the condition is not met

Generate the UserInfo test class UserInfoTest under the Test package

public class UserInfoTest {

    // Validator object
    private Validator validator;

    // Object to validate
    private UserInfo userInfo;

    private Set<ConstraintViolation<UserInfo>> set;
    / / initialization
    @Before
    public void init(a){
        // Initializes the validator
        validator = Validation.buildDefaultValidatorFactory().getValidator();
        userInfo = new UserInfo();
    }

    @Test
    public void testUserInfo(a){
        set = validator.validate(userInfo);
    }

    // Print the result
    @After
    public void after(a){
        set.forEach(item -> {
            // Output error informationSystem.out.println(item.getMessage()); }); }}Copy the code

The test starts with a new UserInfo object in the init method, without assigning the propertiesWhen the validator calls validate, it returns a set. If validation fails, it puts an error message in the set. The userInfo object’s ID is empty, validation fails, and the set holds a message. The @notnull annotation is in effect

The init method calls the setter method of userInfo to assign the id property and executes the test againValidation succeeded. The validation result set is empty, so the output is empty

@ NotEmpty, @ NotBlank

@notempty and @notBlank can both verify that the content is empty.

Add @notempty (message = “the user’s userName cannot be empty “) and @notBlank (message =) to the UserInfo entity class’s userName and Password attributes, respectively “User password cannot be empty “) to test the testUserInfo test methodWhen validation fails, the console outputs the message defined in the annotation

Add a setter to the init method to assign the userName property of the userInfo object to the test again

Init method set userName and password to “”, and run the test again

@notBlank automatically strips whitespace from the string before validation

@Length

Can be used to verify the length of a string, with min and Max and message attributes

Add the @length annotation to the user’s password attribute and set the values of min, Max and message

@length (min = 6, Max = 20, message = "user password cannot be less than 6 characters, cannot be more than 20 characters ")
Copy the code

The test is performed by calling the setter method in the init method to set the user password to less than 6 digits

Call the setter method in the init method to set the user password to more than 20 digits, and run the test again

@Email

@email can only verify that the mailbox format is correct, and @notnull is used to verify that the mailbox is empty

Add the @email annotation to the email attribute of the UserInfo entity class

@email (message = "user's mailbox format is not correct ")
Copy the code

The test is performed by calling setter methods in the init method to assign the Email value

userInfo.setEmail("[email protected]");
Copy the code

@ Min, @ Max

@min and @max can be used for range validation of shaping data

Add @min and @max annotations to the age attribute of the UserInfo entity class to set the age range of the user

@min (value = 18, message = "user must be at least 18 years old ")
@max (value = 100, message = "user cannot be older than 100 ")
Copy the code

Call setter methods in the init method to set the user age

userInfo.setAge(9);
Copy the code

Perform the test

Change the age of the setting

userInfo.setAge(119);
Copy the code

@Past

@past can complete the time check to verify whether the given time is the Past time

Add the @past annotation to the BIRtdDay attribute of the UserInfo entity class

@past (message = "user birthday cannot be a future point in time ")
Copy the code

Set the user’s birthday property in the init method

Calendar calendar = Calendar.getInstance();
calendar.set(2023.1.1);
userInfo.setBirthday(calendar.getTime());
Copy the code

Perform the test

@Size

@size can verify the number of elements in the set. It also has three attributes: min, Max and message

Add the @size annotation to the Friends attribute of the UserInfo entity class

@size (min = 1, message = "user should not have less than 1 friend ")
Copy the code

Set the firends property in the init method

List<UserInfo> friends = new ArrayList<>();
userInfo.setFriends(friends);
Copy the code

Perform the test

This is how the primary constraint annotations are used