Adding a custom annotation to Android Saripaar

2019-02-04 16:19发布

I just started using android saripaar library for a client's app. I wanted to add a custom validation for a field. However, there doesn't seem to be a way to create a custom annotation. I have to manually put in rule in the validator.

How do I create a custom annotation for the same?

1条回答
Viruses.
2楼-- · 2019-02-04 17:22

(Disclosure: I'm the author)

Saripaar v2 allows you to define custom annotations.

Here's how you do it.

Step 1 Define your custom annotation as follows. Make sure you have a RUNTIME retention policy and your annotation must be targeted towards FIELD element types. The message and messageResId attributes are mandatory, so watch the names and the types.

@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
}

Step 2 Define your rule by extending the AnnotationRule class.

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;
    }
}

Step 3 Register your rule.

Validator.registerAnnotation(Haggle.class); // Your annotation class instance

Simple as that. Take a look at the source code if you want to. Saripaar v2 is now available on Maven Central.

查看更多
登录 后发表回答