Thursday, 12 January 2017

Android Creating Form Validation Using Saripaar

In every application that have a form page must be do validation before send data to server. Validation used to keep user input according what that field required.

For example field for email. By put validation in your code, when user write an invalid email, the warning will appears that says "You are enter invalid email, please input a valid email", or etc.

Much of us before knew this library, write a validation function mostly using if and else, right? Imagine that your form contains much field, you will create if else as much as the field, I'm pretty sure it will be so tired.
But know we knew there is a library that helps you to create a validation function. No more using if else or something. This library called Saripaar.

How to use Saripaar library

First, compile the following library :

compile 'com.mobsandgeeks:android-saripaar:2.0.3'

After that, create layout that contains some different EditText like EditText for input name, email, number, password. In this project i use the following layout.

In you java code, this library makes your work more efficient. There are some code that helps you save your time :
  1. @NonEmpty = means your field must be filled.
  2. @Email = means your field for email. By this code, your EdiText will automatically for email. If user input non email format, message error will appears.
  3. @Length = this code determine length of your characters in EditText.
  4. @Password = Means your EditText created for password 
  5. @ConfirmPassword = This code will match your password. This code automatically match with @Password
You can change the default message by using attribute message inside the codes above. Oh ya, don't forget to implements Validator.ValidationListener when you create the java class.

After you implements the validator, you have to implement its method. There are 2 method that you have to implement, there are
  1. onValidationSucceeded()
  2. onValidationFailed(List<ValidationError> errors)
Inside method OnValidationFailed() you just use instance of for validate your EditText, like the following code :

//display the error messageif(view instanceof EditText){
    ((EditText) view).setError(message);
    view.requestFocus();

}else{
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}

For the detail, take a look at the following java class where i hosting my form layout.

That's a simple description about how to create validation using saripaar. Hope this article helps you (especially you who are newbie in android). Thank you.


EmoticonEmoticon