Custom validator
Before writing code, learn about a new annotation@Validator
. Its function is to declare a class as a validator, and its parameters need to be bound to the annotations corresponding to the custom validator. This The role of annotations is the same as @VRequried
and other annotations. Developers can configure verification rules through this annotation;
In this example, we create a simple custom validator to Verify whether the email address entered by the current user already exists;
Create a custom validator annotation:
@Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface VEmailCanUse { /** * @return 自定义验证消息 */ String msg() default ""; }
Implement the IValidator interface and declare the @Validator annotation:
@Validator(VEmailCanUse.class) public class EmailCanUseValidator implements IValidator { public ValidateResult validate(ValidateContext context) { ValidateResult _result = null; if (context.getParamValue() != null) { // 假定邮箱地址已存在 VEmailCanUse _anno = (VEmailCanUse) context.getAnnotation(); _result = new ValidateResult(context.getParamName(), StringUtils.defaultIfBlank(_anno.msg(), "邮箱地址已存在")); } return _result; } }
Test code:
public class VEmailCanUseBean { @VRequried @VEmail @VEmailCanUse 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("ext.email", "demo@163.com"); Map<String, ValidateResult> _results = Validations.get().validate(VEmailCanUseBean.class, _params); // for (Map.Entry<String, ValidateResult> _entry : _results.entrySet()) { System.out.println(_entry.getKey() + " : " + _entry.getValue().getMsg()); } } finally { YMP.get().destroy(); } }
Execution result:
ext.email : 邮箱地址已存在