Android Form Validation Using Saripaar Library Tutorial




Generally, we look for a library that can be used for validation while submitting a form. Let’s take an example, we are creating a signup form that contains Name, Email, password, Confirm password, Phone number etc. Now, you would always prefer to validate the form in client side itself before submitting it to the server. You would like to check if the user has entered email or not, whether user has entered password and it matches to the password entered in confirm-password field etc. We can solve such scenario 2 ways. They are as below –

a. Write code to validate every field by yourself. Think about the test cases that needs to tested and checked. Once all the test cases are passed, Submit the form to server.

b. Use some library to do your job. You just need to write few lines to configure the library.
Then, you are done. This will check the test cases for you and if all test cases are passed, you can submit the form to the server.

What do you think? Which options are better?

Obviously, 2nd option is better because we do not need to bother about the test cases and other stuffs now. Just configure the library and you are done 🙂

There are multiple libraries in the market as of now. For example, saripaar, awesome etc. Each library has it’s own advantage and dis-advantage. Here, we are going to discuss about saripaar library.

Output

Tutorialwing Android Saripaar library example

Tutorialwing Android Saripaar library example

Video Output

Source Code

Getting Started

In this tutorial, we are going to discuss about saripaar library that is used to validate the form.




1. Creating New Project

Follow steps written below to create a new project.
a. Goto File => New => New Project. Then, Write application name as FormValidationSaripaarLibrary and click next.
b. Select Minimum SDK 17 or more => click next => Select Empty Activity => click next => click finish.
If you have followed above process correctly, you will get a newly created project successfully.

1.1 Basic setup to configure Saripaar library

Now, we will do some basic setup to configure the project to use saripaar library. Follow steps below –

1.1.1 Add gradle into app/build.gradle file

Add gradle for saripaar library into app/build.gradle file.

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

Finally, your app/build.gradle file would look like below.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'

    compile 'com.mobsandgeeks:android-saripaar:2.0.3'
}
1.1.2 Different annotations of saripaar library

@NotEmpty: It validates whether the view, with which this annotation is attached, has some value or not. For example,

@NotEmpty

private EditText name;

If we are validating the form and name field is empty, then, it will through error.

@Email: It validate whether the view, with which this annotation is attached, has a valid email address or not. For example,

@Email
private EditText email;

If we are validating the form and email field does not have valid email address, it will through error.

@ConfirmEmail: It validates whether the view, with which this annotation is attached, has same email address as entered in email field or not.

@ConfirmEmail
private EditText confirmEmail

If the email and confirmEmail fields do not have same email address, then, error will be shown whenever form is validated.

@Password: It validate whether the view, with which this annotation is attached, has a valid password or not. For example,

@Password
private EditText password;

If we are validating the form and password field does not have valid password, it will through error.

@ConfirmPassword: It validates whether the view, with which this annotation is attached, has same password as entered in password field or not.

@ConfirmPassword
private EditText confirmPassword;

If the password and confirmPassword fields do not have same password, then, error will be shown whenever form is validated.

@Checked: It validates whether the view is checker or not. If not, then, it will throw error whenever form is validated. For example,

@Checked
private CheckBox termsAndCondition;

If the termAndCondition form is not checked, error will be thrown.

@Length : If you want to validate whether entered text has a valid length or not, you need to use this annotation. You can also check if the user has entered between allowed text length or not. For example,

@Length(max = 12, min = 6, message = "Input must be between 6 and 12 characters")

max and min are used to define maximum and minimum allowed character in the respective fields. message attribute is used to define the message we want to show if there is any validation error.

@Max: This annotation validates whether the field, with which this annotation is attached, has value less than the value defined with this annotation or not. If the field has greater value, error will be thrown. For example,

@Max(value = 10)
private EditText etMaxValue;

If etMaxValue will have value greater than 10, then, error will be thrown whenever form is validated.

@Min: This annotation validates whether the field, with which this annotation is attached, has value greater than the value defined with this annotation or not. If the field has less value, error will be thrown. For example,

@Min(value = 2)
private EditText etMinValue;

If etMinValue will have value less than 2, then, error will be thrown whenever form is validated.

@Or: Suppose you have used 2 annotations( let’s say A and B) attached with any view and you want to validate either A or B. In this scenario you need @Or annotation. For example,

@Min(value = 2)
@Or
@Max(value = 10)
private EditText etValueRange;

Whenever form is validated and etValueRange field contains value either less than 2 or greater than 10, error will be thrown. i.e. Allowed range for etValueRange is between 2 and 10.

These are the common annotations present in saripaar library.




1.2 Start implement Saripaar library

Till now, we have done basic setup in project for saripaar library. Now, we are going to implement saripaar library in our project. We will implement this in following steps.

a. Create an AppActivity activity class where we will write basic setup for validation.
b. Design layout file in activity_main.xml.
c. Write code to validate form in MainActivity.java class.

1.2.1 Creating AppActivity class

Our moto is to create a new activity class (AppActivity.java). AppActivity class will contains basic setup for validation that is common for every class in which you need validations. Then, we will inherit MainActivity class from AppActivity.
AppActivity.java class will contain below code.

package com.tutorialwing.formvalidationsaripaarlibrary;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;

import java.util.List;

public class AppActivity extends AppCompatActivity implements Validator.ValidationListener, View.OnClickListener {

	protected Validator validator;
	protected boolean validated;


	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		validator = new Validator(this);
		validator.setValidationListener(this);
	}

	protected boolean validate() {
		if (validator != null)
			validator.validate();
		return validated;           // would be set in one of the callbacks below
	}

	@Override
	public void onValidationSucceeded() {
		validated = true;
	}

	@Override
	public void onValidationFailed(List<ValidationError> errors) {
		validated = false;

		for (ValidationError error : errors) {
			View view = error.getView();
			String message = error.getCollatedErrorMessage(this);


			// Display error messages
			if (view instanceof Spinner) {
				Spinner sp = (Spinner) view;
				view = ((LinearLayout) sp.getSelectedView()).getChildAt(0);        // we are actually interested in the text view spinner has
			}

			if (view instanceof TextView) {
				TextView et = (TextView) view;
				et.setError(message);
			}
		}
	}

	@Override
	public void onClick(View v) {
		validator.validate();
	}
}

Note: There is no need to define a layout for this AppActivity.

1.2.2 Design layout file

Before we design layout, let’s add some values folder code that we will need soon.

res/values/dimens.xml

<resources>
<dimen name="padding_medium">16dp</dimen>
</resources>

res/values/strings.xml

<resources>
	<string name="app_name">FormValidationSaripaarLibrary</string>
	<string name="name">Name</string>
	<string name="email">Email</string>
	<string name="password">Password</string>
	<string name="confirm_password">Confirm Password</string>
	<string name="phone">Phone</string>
	<string name="alpha_numeric">Alpha Numeric (Max Length 12)</string>
	<string name="submit">Submit</string>
	<string name="confirm_email">Confirm Email</string>
	<string name="terms_and_conditions">I agree to the terms and conditions</string>
	<string name="max_value">Max Value (10)</string>
	<string name="min_value">Min Value(2)</string>
	<string name="value_range">Value between 2 and 10</string>
	<string name="first_field">First field to verify</string>
</resources>

There is no any change in colors.xml and styles.xml files. So, I am not going to add it here.

I have shown some fields in activity_main.xml file. We will validate the data inside these fields using saripaar library. activity_main.xml file would look like below.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:padding="@dimen/padding_medium">

	<RelativeLayout
		android:id="@+id/activity_main"
		android:layout_width="match_parent"
		android:layout_height="wrap_content">

		<EditText
			android:id="@+id/etName"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:ems="10"
			android:hint="@string/name"
			android:inputType="text"/>

		<EditText
			android:id="@+id/etEmail"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etName"
			android:ems="10"
			android:hint="@string/email"
			android:inputType="textEmailAddress"/>

		<EditText
			android:id="@+id/etConfirmEmail"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etEmail"
			android:ems="10"
			android:hint="@string/confirm_email"
			android:inputType="textEmailAddress"/>

		<EditText
			android:id="@+id/etPassword"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etConfirmEmail"
			android:ems="10"
			android:hint="@string/password"
			android:inputType="textPassword"/>

		<EditText
			android:id="@+id/etConfirmPassword"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etPassword"
			android:ems="10"
			android:hint="@string/confirm_password"
			android:inputType="textPassword"/>

		<EditText
			android:id="@+id/etPhone"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etConfirmPassword"
			android:ems="10"
			android:hint="@string/phone"
			android:inputType="phone"/>

		<EditText
			android:id="@+id/etAlphaNum"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etPhone"
			android:ems="10"
			android:hint="@string/alpha_numeric"
			android:inputType="text"/>

		<EditText
			android:id="@+id/etMaxValue"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etAlphaNum"
			android:ems="10"
			android:hint="@string/max_value"
			android:inputType="text"/>

		<EditText
			android:id="@+id/etMinValue"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etMaxValue"
			android:ems="10"
			android:hint="@string/min_value"
			android:inputType="text"/>

		<EditText
			android:id="@+id/etValueRange"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etMinValue"
			android:ems="10"
			android:hint="@string/value_range"
			android:inputType="text"/>

		<EditText
			android:id="@+id/etFirstVerify"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@+id/etValueRange"
			android:ems="10"
			android:hint="@string/first_field"
			android:inputType="text"/>

		<LinearLayout
			android:id="@+id/terms"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@id/etFirstVerify"
			android:orientation="horizontal">

			<CheckBox
				android:id="@+id/termsAccept"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"/>

			<TextView
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:text="@string/terms_and_conditions"/>
		</LinearLayout>

		<Button
			android:id="@+id/submit"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_below="@id/terms"
			android:layout_marginTop="@dimen/padding_medium"
			android:text="@string/submit"/>
	</RelativeLayout>
</ScrollView>
1.2.3 Code to validate form using saripaar library

Now, it’s time to write code to validate these fields. I have written related codes in MainActivity.java file. MainActivity.java class would like below.

package com.tutorialwing.formvalidationsaripaarlibrary;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.mobsandgeeks.saripaar.annotation.Checked;
import com.mobsandgeeks.saripaar.annotation.ConfirmEmail;
import com.mobsandgeeks.saripaar.annotation.ConfirmPassword;
import com.mobsandgeeks.saripaar.annotation.Email;
import com.mobsandgeeks.saripaar.annotation.Length;
import com.mobsandgeeks.saripaar.annotation.Max;
import com.mobsandgeeks.saripaar.annotation.Min;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Or;
import com.mobsandgeeks.saripaar.annotation.Order;
import com.mobsandgeeks.saripaar.annotation.Password;
import com.mobsandgeeks.saripaar.annotation.Pattern;

public class MainActivity extends AppActivity {

	@NotEmpty(message = "Please enter Name")
	private EditText name;

	@Email
	private EditText email;

	@ConfirmEmail
	private EditText confirmEmail;

	@Password(min = 6, message = "Password must have at-least 6 characters")
	private EditText password;

	@ConfirmPassword
	private EditText confirmPassword;

	@Pattern(regex = "[789][0-9]{9}", message = "Please enter valid Phone number")
	private EditText phone;

	@Length(max = 12, min = 6, message = "Input must be between 6 and 12 characters")
	private EditText alphaNumeric;

	@Max(value = 10)
	private EditText etMaxValue;

	@Min(value = 2)
	private EditText etMinValue;

	@Min(value = 2)
	@Or
	@Max(value = 10)
	private EditText etValueRange;

	@Order(value = 1)
	@NotEmpty
	private EditText etFirstVerify;

	@Checked
	private CheckBox termsAndCondition;

	private Button submit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initView();
	}

	private void initView() {
		name = (EditText) findViewById(R.id.etName);
		email = (EditText) findViewById(R.id.etEmail);
		confirmEmail = (EditText) findViewById(R.id.etConfirmEmail);
		password = (EditText) findViewById(R.id.etPassword);
		confirmPassword = (EditText) findViewById(R.id.etConfirmPassword);
		phone = (EditText) findViewById(R.id.etPhone);
		alphaNumeric = (EditText) findViewById(R.id.etAlphaNum);
		termsAndCondition = (CheckBox) findViewById(R.id.termsAccept);
		etMaxValue = (EditText) findViewById(R.id.etMaxValue);
		etMinValue = (EditText) findViewById(R.id.etMinValue);
		etValueRange = (EditText) findViewById(R.id.etValueRange);
		etFirstVerify = (EditText) findViewById(R.id.etFirstVerify);

		submit = (Button) findViewById(R.id.submit);
		submit.setOnClickListener(this);
	}


	@Override
	public void onClick(View v) {
		super.onClick(v);

		if (validated) {
			// Our form is successfully validated, so, do your stuffs here...
			Toast.makeText(this, "Form Successfully Validated", Toast.LENGTH_LONG).show();
		}
	}
}



Few things you must notice here is
a. You must use proper Annotation with field to validate.
b. You must initialise these field. i.e. it should not be null.
c. Check if form is validate or not before performing any operation on click.
d. Inherit Any class form AppActivity(defined above) to use validation.

Output

That’s it for Android Form Validation using Saripaar library. I hope you liked it. 🙂
Now, Run the application and you will see the output as shown above. I have shown a sample form screen and tried to cover most of the annotations present in saripaar library. However, you can design the form as per your need.

If you want to download the source code, go to above link and download it.

Conclusion

Saripaar library plays a important role when you talk about validation in android. Geeks are using it and found it useful. It’s very easy to configure and use it in your application.

Support Us

If you have any suggestion about this post, please comment below. We are looking for someone who helps use to make our tutorial better. Also, If you want tutorials on any topic, you can mail us at tutorialwing@gmail.com. We will try to cover the topic as soon as possible. Connect with us on Facebook, Google+, Twitter and Youtube for more updates.

  • Nick

    Write more, thats all I have to say. Literally,
    it seems as though you relied on the video to make your point.
    You obviously know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us
    something enlightening to read?

  • Oasting Ferrera

    so no localization huh… as strings passed as error messages must be constants and therefore typed out directly in the annotation…