向Android Saripaar添加自定义注释

Ami*_*mit 12 validation user-interface android saripaar

我刚开始使用android saripaar库作为客户端的应用程序.我想为字段添加自定义验证.但是,似乎没有办法创建自定义注释.我必须在验证器中手动输入规则.

如何为其创建自定义注释?

Rag*_*har 21

(披露:我是作者)

Saripaar v2允许您定义自定义注释.

这是你如何做到的.

步骤1按如下方式定义自定义注释.确保您有RUNTIME保留策略,并且您的注释必须针对FIELD元素类型.在messagemessageResId属性是强制性的,所以看的名称和类型.

@ValidateUsing(HaggleRule.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Haggle {
    public int messageResId()   default -1;                     // Mandatory attribute
    public String message()     default "Oops... too pricey";   // Mandatory attribute
    public int sequence()       default -1;                     // Mandatory attribute

    public double maximumAskingPrice();                         // Your attributes
}
Run Code Online (Sandbox Code Playgroud)

步骤2通过扩展AnnotationRule类来定义规则.

public class HaggleRule extends AnnotationRule<Haggle, Double> {

    protected HaggleRule(Haggle haggle) {
        super(haggle);
    }

    @Override
    public boolean isValid(Double data) {
        boolean isValid = false;
        double maximumAskingPrice = mRuleAnnotation.maximumAskingPrice();

        // Do some clever validation....

        return isValid;
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤3注册您的规则.

Validator.registerAnnotation(Haggle.class); // Your annotation class instance
Run Code Online (Sandbox Code Playgroud)

就那么简单.如果您愿意,请查看源代码.Saripaar v2现已在Maven Central上市.