YMP Online Manual
/ 驗(yàn)證框架使用示例
驗(yàn)證框架使用示例
示例代碼:
@Validation(mode = Validation.MODE.FULL) public class UserBase { @VRequried(msg = "{0}不能為空") @VLength(min = 3, max = 16, msg = "{0}長(zhǎng)度必須在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(); } }
執(zhí)行結(jié)果:
username : 用戶名稱長(zhǎng)度必須在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.
功能注解說(shuō)明:
@Validation
:驗(yàn)證模式配置,默認(rèn)為NORMAL;
- NORMAL - 短路式驗(yàn)證,即出現(xiàn)驗(yàn)證未通過(guò)就返回驗(yàn)證結(jié)果;
- FULL - 對(duì)目標(biāo)對(duì)象屬性進(jìn)行全部驗(yàn)證后返回全部驗(yàn)證結(jié)果;
@VField
:自定義待驗(yàn)證的成員或方法參數(shù)名稱;
- name:自定義參數(shù)名稱,在嵌套驗(yàn)證時(shí)上下層參數(shù)以'.'分隔;
- label:自定義參數(shù)標(biāo)簽名稱,若@VField嵌套使用時(shí)功能將不可用;
@VModel
:聲明目標(biāo)對(duì)象是否為JavaBean對(duì)象,將執(zhí)行對(duì)象嵌套驗(yàn)證;