我的Android应用中有一个简单的表单,我使用Android Saripaar进行验证,其中一个字段是电子邮件地址,根据the first example in the docs,它应该如下所示:
@NotEmpty
@Email
private EditText emailEditText;
但是我希望它是一个可选字段,所以我省略了@NotEmpty
注释:
@Email
private EditText emailEditText;
但是当我把它留空时,可以理解为将其标记为无效的电子邮件地址。是否可以在不编写自定义规则的情况下将此字段设为可选字段?
答案 0 :(得分:6)
由于我们需要一个项目的可选电子邮件字段,因此我继续按照this answer制定了规则/注释组合。提到了Rules和Annotations的Saripaar文档。
<强> OptionalEmailRule.java 强>
Public Declare Sub getPEC _
Lib "C:\Users\...somePath...\OPunit0011PUMP.dll" _
(ByVal typeOfPump As Integer, ByVal outflow As Double, ByRef PEC As Double, ByRef RV As Integer)
Public Declare Sub setCEPCI _
Lib "C:\Users\...somePath...\OPunit0011PUMP.dll" _
(ByVal monthIN As Integer, ByVal yearIN As Integer, ByRef RV As Integer)
Function CallPump()
Dim typeOfPump, RV, monthIN, yearIN As Integer
typeOfPump = 9
Dim outlfow, PEC As Double
outflow = 100
monthIN = 5
yearIN = 2008
Call getPEC(typeOfPump, outflow, PEC, RV)
Call setCEPCI(monthIN, yearIN, RV)
End Function
<强> OptionalEmail.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);
}
}
}
内部验证活动
注册注释
@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);