Problem description

@Data
public class RegisterForm {

    @length (min = 4, message = "username must be at least 4 characters long ")
    @notblank (message = "user name cannot be blank ")
    private String username;

    @notblank (message = "password cannot be blank ")
    @length (Max = 20, message = "password Length up to 20 characters ")
    @length (min = 8, message = "Password Length is at least 8 characters ")
    @ the Pattern (regexp = "^ [\ \ w_ -] 8, 20} {$", message =" the password format error ")
    private String password;

    @notblank (message = "Student id cannot be blank ")
    @length (min = 9, Max = 10, message = "student number is incorrect ")
    private String sno;

}
Copy the code

The above code checks the order, if all parameters are empty, annotations all hit, will return a random verification error message.

That is, the order of ObjectError fetched by BindingResult#getAllErrors() is random

The solution

Add multiple GroupX groups to the @GroupSequence, in the desired order, to the group attribute of the Validated annotation, and add group.class to the @Validated value attribute in the Controller method

// GroupA.java
public interface GroupA {}

// GroupB.java
public interface GroupB {}

// GroupC.java
public interface GroupC {}

// GroupD.java
public interface GroupD {}

// GroupE.java...

// Group.java
@GroupSequence({GroupA.class, GroupB.class, GroupC.class, GroupD.class, ... })
public interface Group {}
Copy the code
@Data
public class RegisterForm {

    @length (min = 4, message = "user name Length is at least 4 characters ", group = groupa.class)
    @notblank (message = "user name cannot be blank ", group = groupb.class)
    private String username;

    @notblank (message = "password cannot be blank ", group = groupc.class)
    @length (Max = 20, message = "password Length up to 20 characters ", group = groupd.class)
    @length (min = 8, message = "password Length is at least 8 bits ", group = groupd.class)
    @ the Pattern (regexp = "^ [\ \ w_ -] 8, 20} {$", message =" the password format error ", group = GroupE. Class)
    private String password;

}
Copy the code

    @PostMapping("register")
    public Response register(@RequestBody @Validated(Group.class) RegisterForm form) {
        //...
    }

Copy the code