preface

Make writing a habit together! This is the 7th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Every application software is inseparable from data verification, such as length verification and non-null verification of the field content submitted by users when submitting forms. Some partners still use the most primitive verification method when doing field content verification — obtaining field content and verifying the content with if-else. This verification method is of course ok, but it requires many lines of code to implement the verification function, which makes our coding efficiency and code readability reduced a lot. So today, let’s introduce another way to use @VALID annotation to implement field verification.

Field calibration

First we will create a new student class (class is also very simple, only name and age two fields) 👇

/** ** *@description: Student
 * @author: Zhuang Ba. Liziye *@create: the 2022-02-16 and * * /
public class Student {

    /** * Student name */
    private String name;

    /** * Student age */
    private Integer age;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age; }}Copy the code

Next, we will create a new Cotroller to simulate the operation process of adding students 👇

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** * Simulate the process of adding students *@description: StudentController
 * @author: Zhuang Ba. Liziye *@create: the 2022-02-16 11:19 * * /
@RestController
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/add")
    public String add(Student student){
        
        return "Added successfully"; }}Copy the code

Use if-else for field validation

If the student name must not be empty and the length cannot exceed 10, then we will use the previous validation method (if-else) to write 👇

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** * Simulate the process of adding students *@description: StudentController
 * @author: Zhuang Ba. Liziye *@create: the 2022-02-16 11:19 * * /
@RestController
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/add")
    public String add(Student student){

        String name = student.getName();

        if(name == null || name.trim().length() == 0) {return "Student names cannot be blank!";
        }else if (name.trim().length() > 10) {return "Student name length out of limit!";
        }
        return "Added successfully"; }}Copy the code

Next, let’s test whether the validation works We can see that the validation is perfectly fine, satisfying the requirement of the student name restriction. Here comes a new requirement: the age field is also non-empty and ranges from 1 to 100, so we need to modify the code again 👇

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** * Simulate the process of adding students *@description: StudentController
 * @author: Zhuang Ba. Liziye *@create: the 2022-02-16 11:19 * * /
@RestController
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/add")
    public String add(Student student){

        String name = student.getName();
        if(name == null || name.trim().length() == 0) {return "Student names cannot be blank!";
        }else if (name.trim().length() > 10) {return "Student name length out of limit!";
        }

        Integer age = student.getAge();
        if(age == null) {return "Student age cannot be blank!";
        }else if (age < 1 || age > 100) {return "Student age error, please check again!";
        }

        return "Added successfully"; }}Copy the code

We still use if-else for field verification, which can also be perfect to achieve the requirements. What if there are 10 or 20 fields that need to be verified? There are only two fields in the Student class, and the Student class already has ten or more lines of code to check these two fields. If there are more fields, the Student class will have dozens or even a hundred lines of code to check 😮, and the method will be very bloated and unreadable.

Some of you might say: We can write a separate if-else check method to make the code cleaner. This method does make the code cleaner and improves the readability of the code, but it does not reduce the number of if-else statements.

The @valid annotation is used to implement (•̀ ω •́)y ~

Field validation is implemented using the @VALID annotation

We still need to import dependencies before using the @valid annotation (we don’t need to import dependencies for Spring Boot projects, spring-boot-starter-web already does this for us) 👇

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1. 0.Final</version>
</dependency>
 
<dependency>
	<groupId>org.hibernate.validator</groupId>
	<artifactId>hibernate-validator</artifactId>
</dependency>
Copy the code

Next we make a small change to the student class and Cotroller 👇

package com.example.shiro.controller;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.NotNull;

/** ** *@description: Student
 * @author: Zhuang Ba. Liziye *@create: the 2022-02-16 and * * /
public class Student {

    /** * Student name */
    @notnull (message = "Valid check: Please enter student name!" )
    @length (message = "name cannot exceed {Max} characters ", Max = 10)
    private String name;

    /** * Student age */
    @notnull (message = "Valid check: Please enter student age ")
    @range (message = "age Range {min} to {Max} ", min = 1, Max = 100)
    private Integer age;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age; }}Copy the code
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/** * Simulate the process of adding students *@description: StudentController
 * @author: Zhuang Ba. Liziye *@create: the 2022-02-16 11:19 * * /
@RestController
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/add")
    public String add(@Valid Student student, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            return bindingResult.getAllErrors().get(0).getDefaultMessage();
        }
        return "Added successfully"; }}Copy the code

As you can see, in the Cotroller we have added two sections: @valid and BindingResult. Here is a simple explanation:

  • Adding the @valid annotation to the front of the student object indicates that we need to validate the properties in the object. This validates the contents of the annotations added to the student class.
  • BindingResult is the “companion” of the @Valid annotation. BindingResult stores the validation result after the validation information of the entity class.

Let’s try again to check if it works 👇

As we can see, the result of field validation is exactly what we expected, and it also makes the code much more readable, isn’t it nice😄

Finally, I’ll summarize the common validation annotations in entity classes:

  • @NULL: Annotated elements must be Null
  • @notnull: Annotated elements cannot be NULL
  • @assertTrue: This field can only be true
  • @ASSERtFalse: The value of this field can only be false
  • @min (value) : The annotated element must be a number whose value must be greater than or equal to the specified minimum value
  • @max (value) : The annotated element must be a number whose value must be less than or equal to the specified maximum value
  • @decimalmin (” value “) : The annotated element must be a number, verifying the minimum value of a decimal
  • @decimalmax (” value “) : The annotated element must be a number, verifying the maximum number of decimals
  • @size (Max,min) : Check whether the Size of the field is between min and Max. The value can be a string, array, set, or Map
  • @past: The annotated element must be a Past date
  • @Future: The annotated element must be a Future date
  • @pattern (regexp = “[ABC]”) : The annotated element must conform to the specified regular expression.
  • @email: The annotated element must be an E-mail address
  • @length (Max =5,min=1,message= “Length between 1 and 5”) : Checks whether the Length of the field to which it belongs is between min and Max
  • @notempty: The annotated string must be non-empty
  • @range: Annotated elements must be in the appropriate Range
  • NotBlank: cannot be null, Spaces will be ignored when checked
  • @notempty: cannot be empty, where empty means empty string

summary

My experience is limited, some places may not be particularly in place, if you think of any questions when reading, welcome to leave a message in the comments section, we will discuss one by one 🙇

Please take a thumbs up and a follow (✿◡‿◡) for this article ~ a crab (●’◡’●)

If there are mistakes in the article, welcome to comment correction; If you have a better, more unique understanding, you are welcome to leave your valuable ideas in the comments area.

Love what you love, do what you do, listen to your heart and ask nothing