springboot JSR303資料校驗
阿新 • • 發佈:2021-08-05
JSR303資料校驗
@Component //註冊bean @ConfigurationProperties(prefix = "person") @Validated //資料校驗 public class Person { @Email(message="郵箱格式錯誤") //Cannot resolve symbol 'Email' private String name; }
Cannot resolve symbol ‘Email’
新增依賴
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.1.Final</version> </dependency>
常見引數
@NotNull(message="名字不能為空") private String userName; @Max(value=120,message="年齡最大不能查過120") private int age; @Email(message="郵箱格式錯誤") privateString email; 空檢查 @Null 驗證物件是否為null @NotNull 驗證物件是否不為null, 無法查檢長度為0的字串 @NotBlank 檢查約束字串是不是Null還有被Trim的長度是否大於0,只對字串,且會去掉前後空格. @NotEmpty 檢查約束元素是否為NULL或者是EMPTY. Booelan檢查 @AssertTrue 驗證 Boolean 物件是否為 true @AssertFalse 驗證 Boolean 物件是否為 false 長度檢查 @Size(min=, max=) 驗證物件(Array,Collection,Map,String)長度是否在給定的範圍之內 @Length(min=, max=) string is between min and max included. 日期檢查 @Past 驗證 Date 和 Calendar 物件是否在當前時間之前 @Future 驗證 Date 和 Calendar 物件是否在當前時間之後 @Pattern 驗證 String 物件是否符合正則表示式的規則 .......等等 除此以外,我們還可以自定義一些資料校驗規則