Adding a custom annotation to Android Saripaar
Asked Answered
B

1

13

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?

Blader answered 28/1, 2014 at 12:33 Comment(1)
I'm working on Saripaar v2 and it supports custom annotations. Will post an answer when it's ready.Cavity
C
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.

Cavity answered 9/12, 2014 at 8:19 Comment(5)
Where is HagglingPolicy defined?Augend
@T.Coutlakis, similified the example.Cavity
@RagunathJawahar even after going through your source code its not clear what kind of parameters the annotations are expecting can you please share a blog / article or i would really love to help you in documenting the projectRubric
Maybe you can just add the optional validator. @OptionalEmailDunseath
Hi Ragunath Jawahar - Thanks for these awesome lib, What i am looking for is Or validation against field means like login with pin or userId at-least one of them should filled and check min and max length can we do these using saripaar if yes please give me some tips thanksWindup

© 2022 - 2024 — McMap. All rights reserved.