YMP 온라인 매뉴얼
/ 验证框架使用示例
验证框架使用示例
示例代码:
@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对象,将执行对象嵌套验证;