天天看點

spring @Validated 分組校驗

轉載自:https://juejin.im/post/5cb46bdb5188251aca7342b9

分組校驗

public class ValidationDemo {
    private String id;

    @Length(min = 2, max = 6, message = "使用者名長度要求在{min}-{max}之間")
    @NotNull(message = "使用者名不可為空")
    private String userName;

    // 表示分組為Adult時使用該校驗規則
    @Email(message = "郵箱格式錯誤")
    @NotBlank(message = "郵箱不可為空", groups = {ValidationDemo.Adult.class})
    private String email;

    @Past(message = "出生日期錯誤")
    private Date birthDay;

    @Min(value = 18, message = "年齡錯誤")
    @Max(value = 80, message = "年齡錯誤")
    private Integer age;

    @Range(min = 0, max = 1, message = "性别選擇錯誤")
    private Integer sex;

    // 添加兩個分組
    public interface Adult {
    }

    public interface Minor {
    }
}
           

測試一下

// 這裡将分組設定為Minor,目的是不校驗郵箱字段
@RequestMapping(value = "validation", method = RequestMethod.POST)
public JsonResult validation(@Validated({ValidationDemo.Adult.class}) @RequestBody ValidationDemo demo) {
    return null;
}

RequestBody:
{
  "age": 0,
  "birthDay": "2019-04-14T10:39:08.501Z",
  "email": "",
  "id": "string",
  "sex": 0,
  "userName": "string"
}
Response:
{
  "code": 1,
  "msg": "[\"郵箱不可為空\"]",
  "total": 0,
  "totalpage": 0
}
           
RequestBody:
{
  "age": 0,
  "birthDay": "2019-04-14T10:39:08.501Z",
  "email": "",
  "id": "string",
  "sex": 0,
  "userName": "string"
}
Response:
{
  "code": 0,
  "data": [
    {}
  ],
  "extra": "string",
  "msg": "string",
  "result": {},
  "total": 0,
  "totalpage": 0
}
           

由此可見,分組驗證已經生效

繼續閱讀