手写一个验证邮箱字段的注解:
首先项目中需要引入包:javax.validation:validation-api-1.1.0.Final.jar
好,开始写一个注解
@Documented
@Constraint(validatedBy = EmailValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER, ElementType.CONSTRUCTOR})//注解作用对象
@Retention(RetentionPolicy.RUNTIME)//注解作用时间
public @interface Email {
boolean allowEmpty() default true;
String message() default "is not a email";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
EmailValidator.java
public class EmailValidator implements ConstraintValidator<Email, String> {
boolean allowEmpty = false;
@Override
public void initialize(Email email) {
allowEmpty = email.allowEmpty();
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
return (allowEmpty && StringUtils.isEmpty(s)) || (StringUtils.isNotEmpty(s) && s.matches ("^[a-z_0-9.-]{1,64}@([a-z0-9-]{1,200}.){1,5}[a-z]{1,6}$"));
}
}
使用:在标识email的字段上添加注解@Email就能校验这个是否满足email的判断规则