普通校驗
導入依賴:
默認的報錯:沒有提示具體的屬性
設置自己的錯誤信息提示:創建 ValidationMessages.properties
內容如下:
user.id.notnull = id 不能為空 user.username.size = username 長度為5-10 user.age.min = age 年齡最小為1 user.age.max = age 年齡最大為100 user.email.pattern= email 格式不正確
實體類注解上設置message屬性,,使用{}引入 VallidationMessages.properties 內容:
public class User { @NotNull(message = "{user.id.notnull}") private Integer id; @Size(min = 5,max = 10,message = "{user.username.size}") // @Size 字符串長度 private String username; @DecimalMin(value = "1",message = "{user.age.min}") // @DecimalMin 數值最小 @DecimalMax(value = "100",message = "{user.age.max}") private Integer age; @Email(message = "{user.email.pattern}") private String email; }
測試:
自定義錯誤信息,顯示指定屬性錯誤
分組校驗
不同的請求,實現不同的校驗。。
創建兩個空接口,標識作用:
ValidationGroup01 ValidationGroup02
修改User:
public class User { @NotNull(message = "{user.id.notnull}",groups = {ValidationGroup01.class,ValidationGroup02.class}) private Integer id; @Size(min = 5,max = 10,message = "{user.username.size}",groups = {ValidationGroup01.class}) // @Size 字符串長度 private String username; @DecimalMin(value = "1",message = "{user.age.min}") // @DecimalMin 數值最小 @DecimalMax(value = "100",message = "{user.age.max}") private Integer age; @Email(message = "{user.email.pattern}",groups = {ValidationGroup01.class}) private String email; }
controller中表明你要使用哪個分組校驗:
public void addUser(@Validated(value = ValidationGroup01.class) User user, BindingResult result){ ... }
只會校驗user中groups標注了ValidationGroup01.class 的字段。。
到此這篇關于springboot中validator數據校驗的文章就介紹到這了,更多相關springboot validator數據校驗內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_36022463/article/details/120733871