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?

amalBit
  • 12,041
  • 6
  • 77
  • 94
Amit
  • 3,952
  • 7
  • 46
  • 80

1 Answers1

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.

Ragunath Jawahar
  • 19,513
  • 22
  • 110
  • 155
  • Where is HagglingPolicy defined? – T.Coutlakis Mar 19 '15 at 21:21
  • @T.Coutlakis, similified the example. – Ragunath Jawahar Mar 21 '15 at 05:26
  • 1
    @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 project – Gaurav Sarma Mar 18 '16 at 07:51
  • Maybe you can just add the optional validator. `@OptionalEmail` – blackdog Jul 11 '16 at 07:19
  • 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 thanks – Sushant Gosavi Mar 13 '18 at 04:41