'java springboot: Field validation problems caused by using @Valid [duplicate]

There are two controller methods, one is query and the other is add. The two methods use the same entity class, but the fields that need to be input are different. Both use @Valid. The query only uses one check but must also be filled in with add extra checksum.The query method uses name, and the add method uses name, remarks, and status.

controller

@PostMapping("/user/list")
public Doc getUser(@Valid @RequestBody UserVo user, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
    return new Doc(service.getPage(user, page, limit));
}

@PostMapping("/user/add")
public Doc addUser(@Valid @RequestBody UserVo user) {
    return new Doc(service.add(user));
}

UserVo

public class UserVo {

    private static final long serialVersionUID =  1L;

    /** select and add */
    @Size(max = 128, message = "名称过长!")
    private String name;

    /** add */
    @Size(max = 255, message = "备注内容过长!")
    private String memo;

    /** add */
    @NotNull(message = "请输入状态!")
    private Integer status;
}


Solution 1:[1]

You can create custom validator and implement it by using @Validated annoation in springboot by creating different groups , for reference you can take some insights from this article https://www.baeldung.com/spring-valid-vs-validated

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vanshikamalhotra