驗證框架使用範例
範例程式碼:
@Validation(mode = Validation.MODE.FULL) public class UserBase { @VRequried(msg = "{0}不能为空") @VLength(min = 3, max = 16, msg = "{0}长度必须在3到16之间") @VField(label = "用户名称") private String username; @VRequried @VLength(max = 32) private String password; @VRequried @VCompare(cond = VCompare.Cond.EQ, with = "password") private String repassword; @VModel @VField(name = "ext") private UserExt userExt; // // 此处省略了Get/Set方法 // } public class UserExt { @VLength(max = 10) private String sex; @VRequried @VNumeric(min = 18, max = 30) private int age; @VRequried @VEmail private String email; // // 此处省略了Get/Set方法 // } public static void main(String[] args) throws Exception { YMP.get().init(); try { Map<String, Object> _params = new HashMap<String, Object>(); _params.put("username", "lz"); _params.put("password", 1233); _params.put("repassword", "12333"); _params.put("ext.age", "17"); _params.put("ext.email", "@163.com"); Map<String, ValidateResult> _results = Validations.get().validate(UserBase.class, _params); // for (Map.Entry<String, ValidateResult> _entry : _results.entrySet()) { System.out.println(_entry.getValue().getMsg()); } } finally { YMP.get().destroy(); } }
#執行結果:
username : 用户名称长度必须在3到16之间 repassword : repassword must be eq password. ext.age : ext.age numeric must be between 30 and 18. ext.email : ext.email not a valid email address.
功能註解說明:
@Validation
:驗證模式配置,預設為NORMAL;
- NORMAL - 短路式驗證,即出現驗證未通過就傳回驗證結果;
- FULL - 對目標物件屬性進行全部驗證後傳回全部驗證結果;
@VField
:自訂待驗證的成員或方法參數名稱;##name:自訂參數名稱,在嵌套驗證時上下層參數以'.'分隔;label:自訂參數標籤名稱,若@VField嵌套使用時功能將不可用;
@VModel
:宣告目標物件是否為JavaBean對象,將執行物件嵌套驗證;