Spring @ valid @ validated implementation validation

Time:2020-10-11

There are some comments on the validation of attributes
@Notblank: only used on string, the value cannot be null, and the length after trim is greater than zero. A string that is not null, not all spaces
@Notnull: cannot be null, but can be a zero length string
@Notempty: cannot be null, length greater than zero
@Null: must be null
@Min (value): number, the value must be greater than or equal to the specified value
@Max (value): number, the value must be equal to the specified value
@Decimalmin (value): number, the value must be greater than or equal to the specified value
@Decimalmax (value): number, the value must be equal to the specified value
@Digits (integer, fraction): a number, the value must be within the acceptable range @ digits (integer = 3, fraction = 2) 111.22 meets the requirements, 1111.22 does not meet the requirements, and the integer part is 4 bits, so it does not meet the requirements
@Size (min = V1, max = V2): V1 < = value < = V2
@Asserttrue: must be true
@Assertfalse: must be false
@Past: must be in the past
@Future: must be a future date
@Pattern (regex =, flag =): matches the specified regular expression

@Valid: can be used on method parameters, methods, and properties. Used for nested validation. Nested validation means that ClassB exists in the properties of classA, and the properties of ClassB also need to be verified.

@Validated: can be used on method parameters, methods, not properties. The function of grouping is provided, and different verification mechanisms are adopted according to the grouping when parameters are passed in. For example, for the user’s userid, the userid must be null when creating a new user. When updating users, the userid must not be empty and cannot be all blank. The user ID is grouped into two groups: add and update.

@Valid instance

Book definition


public class Book {

  @NotBlank(message = "bookID is mandatory, can not be blank")
  public String bookID;
  
  @Size(min=5, max=20)
  @NotBlank(message = "bookName is mandatory, can not be blank")
  public String bookName;
  public String author;
  
  @Valid
  public List<ChapterInfo> chapterList;
  
  public Book(String id, String name, String auth) {
    bookName = name;
    author = auth;
    bookID = id;
  }
}

Chapter info definition


public class ChapterInfo {
  @Min(0)
  public Long chapterID;
  
  @NotBlank
  @Size(min=5, max=50)
  public String chapterName;
  
  @Size(min=5, max=20)
  public String contentID;
}

BookController


@RestController
@RequestMapping("/bookcontroller")
public class BookController {

  private List<Book> bookList = new ArrayList();
  
  @ResponseBody
  @RequestMapping("/addBookToList")
  public boolean addBookToList(@Valid @RequestBody Book b) {
    System.out.println(b.bookName);
    
    bookList.add(b);
    
    return true;
  }
  
  @InitBinder
  private void activateDirectFieldAccess(DataBinder dataBinder) {
    dataBinder.initDirectFieldAccess();
  }
  
}

Postman verification

You can see that the chapter name of the chapterinfo in the chapterlist is blank, and the verification fails

@Validated instance


public class User {
  
  @NotBlank
  public String name;
  
  @NotBlank
  public String address;
  
  @Min(1)
  public int age;

  public boolean isMan;
  
  @NotBlank(groups = {Update.class})
  @Null(groups = {Add.class})
  public String usrID;
  
  public interface Add{}
  
  public interface Update{}
  
  
  public User(String name, String addr, int age, boolean isMan) {
    this.name = name;
    this.address = addr;
    this.age = age;
    this.isMan = isMan;
  }

}

Where @ notblank (groups = is used for the usrid attribute{ Update.class }) and @ null (groups =){ Add.class }) comments. intend:
(1) When updating user, usrid cannot be blank (to find user through usrid to update)
(2) When adding user, usrid must be empty (to generate a new user, user ID will be assigned)


@RestController
@RequestMapping("/registcontroller")
public class RegistController {

  List<User> usrList = new ArrayList();
  
  
  @PostMapping(path="/adduser")
  @ResponseBody
  public User addUser(@RequestBody @Validated({User.Add.class}) User usr, BindingResult result) {
    
    if (result.hasErrors()) {
      List<ObjectError> list = result.getAllErrors();
      FieldError error = (FieldError)list.get(0);
      System.out.println(error.getObjectName() + "," + error.getField() + "," + error.getDefaultMessage());
      return null;
    }
    User user = new User(usr.name, usr.address, usr.age, usr.isMan);
    String usrID = usrList.size() + "";
    
    user.usrID = usrID;
    
    return user;
  }
}

Validated group validation (add) is performed on the incoming parameter of addUser. If the usrid of the incoming user is not blank, an error will occur.

Postman verification

When usrid does not exist

Return the newly added user normally

When usrid is specified

error

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

Rust and python: why rust can replace Python

In this guide, we compare the rust and python programming languages. We will discuss the applicable use cases in each case, review the advantages and disadvantages of using rust and python, and explain why rust might replace python. I will introduce the following: What is rust? What is Python? When to use rust When to […]