(Reddit re-post) Validation in Android – Why I ‘scratched my itch’ and how it saves our time

Original post on Reddit.

I have been working on Android since 2009. I never gave much thought about validation until I did this enterprise application for one of my clients. The application had a dozen of forms with all kinds of validations, starting from required fields, regular expressions to server validations. Validation became a pain in the neck and it was so annoying.

I tried googling for validation frameworks and there were a few which gave a jump start. However, they were insufficient for complex validations or forced me to use their own EditText widgets. Being desperate and frustrated I began authoring this library about 3 AM one day and in the next 3 hours ended up with something that was easy to use.

I posted it on GitHub (Yeah, licensed under Apache 2.0) and after receiving a suggestion from a developer on StackOverflow, I added annotations. Here are some of the examples that will clearly show you the difference when using traditional validation techniques and when using the Android Saripaar UI validation library.

Traditional – Required Field

String username = userNameEditText.getText().toString();
int usernameLength = username.length();
if (usernameLength == 0) {
    // Notify the user that username is required.
} else if (usernameLength > 3) {
    // Notify the user that username is too short.
}

Saripaar – Required Field

@Required(order = 1, messageResId = R.string.username_required)
@TextRule(order = 2, minLength = 3, message = "Too short :(")
private EditText usernameEditText;

Saripaar – Email (Optional or Valid)

@Email(order = 1, messageResId = R.string.email_invalid)
private EditText emailEditText;

Saripaar – Email (Required and Valid)

@Required(order = 1, messageResId = R.string.email_required)
@Email(order = 1, messageResId = R.string.email_invalid)
private EditText emailEditText;

This is how concise your code could get when you use Saripaar and these examples just showcase the tip of the iceberg.

You can validate IP addresses, regular expressions, numbers, etc., Some of the salient features that improve productivity when you use Android Saripaar are,

  • Annotation support
  • Custom Rules
  • Complex Rules (And, Or, Composite And, Composite Or, etc.,)
  • Asynchronous validation (You don’t have to worry about threading and AsyncTasks.,)
  • Rule only validation (If you are validating against a database or a network connection.,)

We use this extensively for our projects at Mobs & Geeks and have achieved significant productivity in most of the projects.

Saripaar does a remarkable job of offloading the validation logic from your business logic thereby allowing to save a lot of time testing your code.

If you are someone who hates dependencies and has trouble with validations, give it a try. The source is available for download from the Android Saripaar GitHub page.

Advertisements