由于我们需要一个项目的可选电子邮件字段,因此我继续并根据此答案进行了规则/注释组合。参考 Saripaar 文档的规则和注释。
可选EmailRule.java
public class OptionalEmailRule extends AnnotationRule<OptionalEmail, String> {
protected OptionalEmailRule(final OptionalEmail email) {
super(email);
}
@Override
public boolean isValid(final String email) {
if(TextUtils.isEmpty(email)){
//email is empty and therefore valid
return true;
}
else{
//email is not empty, proceed as usual
boolean allowLocal = mRuleAnnotation.allowLocal();
return EmailValidator.getInstance(allowLocal).isValid(email);
}
}
}
可选电子邮件.Java
@ValidateUsing(OptionalEmailRule.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface OptionalEmail {
boolean allowLocal() default false;
int sequence() default -1;
int messageResId() default -1;
String message() default "Invalid email";
}
内部验证活动
注册注解
Validator.registerAnnotation(OptionalEmail.class);
注释字段
@OptionalEmail
public EditText editEmail;