Skip to content

Android Saripaar Basics

ragunathjawahar edited this page Nov 24, 2012 · 5 revisions

Android Saripaar is a simple rule-based validation library for Android. The library began with the following design goals:

  • To create a powerful and easy to use library.
  • Eliminate boiler-plate code.
  • Isolate validation logic.
  • Make asynchronous validations seamless.

And these goals have come to fruition with Saripaar.

Basics

  1. Saripaar is a rule-based library, so every validation logic goes inside its Rule.
  2. Rules are validated in the order they are added, starting with annotations.
  3. Validation results are delivered via callbacks in the Validator.ValidationListener interface.

Rule

The Rule class is the essence of the library. It's purpose it to isolate validation logic from the rest of the code. It is not tied to any View and therefore you can reuse rules if necessary. The built-in rules of the Rules class are classic examples for reusing rules. Rules contain a failureMessage and a isValid(T) method.

To write a rule you extend the Rule class or instantiate it anonymously and override its isValid(T) method.

Rule<EditText> allowMartiansOnlyRule = new Rule<EditText>("Oops… only Martians allowed.") {

    @Override
    public boolean isValid(EditText planetEditText) {
        String residentPlanet = planetEditText.getText().toString();
        return "Mars".equalsIgnoreCase(residentPlanet);
    }
};

Not just trivial rules, you can also write long running operations in a Rule. Validation logic that involves network operations, database queries, file access, content providers, intensive computations, etc., can be enclosed within a Rule. All with the luxury of writing them synchronously.

Rule<EditText> domainNameMustBeUniqueRule = new Rule<EditText>("Domain name already taken.") {

    @Override
    public boolean isValid(EditText domainNameEditText) {
        String domainName = domainNameEditText.getText().toString();

        SomeRestFacade facade = new SomeRestFacade(API_KEY);
        return facade.isDomainNameAvailable(domainName);
    }
};

And when you need to validate those, Saripaar will offload them to a background AsyncTask and report back with appropriate callbacks.

Validator

The Validator does all the heavy lifting for you by validating rules against their Views. It has two public constructors, Validator(Activity) and Validator(Fragment). Validations can be done synchronously by calling the Validator.validate() or asynchronously by calling the Validator.validateAsync() method. The results of the validation are delivered via callback methods in the Validation.ValidationListener interface.

Clone this wiki locally