Android Form Validation Using Android AwesomeValidation Library Tutorial




Validating any data before submitting it to the server has always been a tricky but easier task when you are using a proper library. If you are trying to achieve the same goal without using any library, it would be an extra headache to cover all the test cases. Specially when you have many fields in your page. So, using library is always a better choice. There are so many libraries in the market that can be used for validation. For example, Android Saripaar library for Validation, Android AwesomeValidation library for validation etc. I have already covered Android Saripaar library. If you want, you can go through this post. In this post, I am going to discuss about Android AwesomeValidation library. Like Android Saripaar library, AwesomeValidation is also easy to setup and use in the android application. You might be thinking which options are better? which library should i use? etc. You will get answer to these questions in this post.

AwesomeValidation library supports following validation rules.
String Type
Numeric
AlphaNumeric
IP Address
Web Url
Phone Number
Year

SourceCode

Output

Tutorialwing Android AwesomeValidation Library tutorial

Tutorialwing Android AwesomeValidation Library tutorial

Video Output

Getting started

In this tutorial, you will learn how to use Android AwesomeValidation library to validate any form before submitting it to the server.

1. Creating New Project

Follow steps written below to create a new project.
a. Goto File => New => New Project. Then, Write application name as FormValidationAwesomeLibrary 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. If you want to know how to create a project in detail, you can go to creating first project




1.1 Basic setup to configure Android AwesomeValidation library

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

1.1.1 Add gradle into app/build.gradle file

Add gradle for Android AwesomeValidation library into app/build.gradle file.

compile 'com.basgeekball:awesome-validation:2.0'

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.basgeekball:awesome-validation:2.0'
}

1.2 Set up user interface to implement android AwesomeValidation library

Next thing that we need now is UI in which we will use this awesome library. So, we will create an UI now. You need to follow following steps –

1.2.1 Values Folder

I am adding these values folder before creating ui so that you do not get errors while doing copy/paste the code.
res ==> values ==> dimens.xml file

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

res ==> values ==> strings.xml file

<resources>
	<string name="app_name">FormValidationAwesomeLibrary</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="age">Age</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="invalid_name">Please enter a valid Name</string>
	<string name="invalid_email">Please enter a valid email</string>
	<string name="invalid_confirm_email">Email does not match</string>
	<string name="invalid_password">Please enter a valid password</string>
	<string name="invalid_confirm_password">Password does not match</string>
	<string name="invalid_phone">Please enter a valid Phone</string>
	<string name="invalid_age">Age must be between 12 and 60.</string>
</resources>

There are no changes in colors.xml and styles.xml files, so i am not going to add these here. If you need reference, you can download the sourcecode.

1.2.2 Creating sign up form to use AwesomeValidation library

Everything is ready now. So, let’s create the UI. In this tutorial, we are going to see how to validate a sample sign up form using AwesomeValidation library. This sample signup form will contain name, email, confirm email, password, confirm password, phone and age.

Now, open res ==> layout ==> activity_main.xml file and copy/paste below code to create sign up form that contains these fields.
res ==> layout ==> activity_main.xml file code

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

	<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/etAge"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_below="@+id/etPhone"
		android:ems="10"
		android:hint="@string/age"
		android:inputType="text"/>

	<Button
		android:id="@+id/submit"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_below="@id/etAge"
		android:layout_marginTop="@dimen/padding_medium"
		android:text="@string/submit"/>
</RelativeLayout>



Now, the next task is accessing these fields in java file. So, i am going to write the code to show how you can access these fields. Open MainActivity.java file and write below code into it.

MainActivity.java file code

package com.tutorialwing.formvalidationawesomelibrary;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

	private EditText name;

	private EditText email;
	private EditText confirmEmail;

	private EditText password;
	private EditText confirmPassword;

	private EditText phone;
	private EditText age;

	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);
		age = (EditText) findViewById(R.id.etAge);

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

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.submit:
				submitForm();
				break;
		}
	}
}

1.3 Start using AwesomeValidation library

Now, we are ready to use AwesomeValidation library. We will see implementation of AwesomeValidation library in three steps.
1. Declaring validation style
2. Add required validations
3. Set a point when you want to trigger validation

1.3.1 Declaring Validation Style

To implement validation in the form, you will need to create an instance of AwesomeValidation. While creating validation style, you need to take care of the cases where you are going to implement this library. AwesomeValidation library supports following style type
BASIC
COLORATION
UNDERLABEL
TEXT_INPUT_LAYOUT
Let’s get some ideas about these types
A. BASIC Style Type: In this style type, you will get error message below the View (EditText, Spinner etc.) Also, You will see the message one by one. If you want to use this type of validation style, you can declare validation object as below

AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);

B. COLORATION Style Type: In this style type, Incorrect input will be highlighted. You can set the color as well to show the incorrect input. However, the default color is red. If you want to use this type of validation style, you can declare validation object as below

AwesomeValidation mAwesomeValidation = new AwesomeValidation(COLORATION);
mAwesomeValidation.setColor(Color.YELLOW);  // optional, default color is RED if not set

C. UNDERLABEL Style Type: In this style type, you will get error message below the View all at a time. This is difference between BASIC and UNDERLABEL style type. If you want to use this type of validation, you can declare validation object as below.

AwesomeValidation mAwesomeValidation = new AwesomeValidation(UNDERLABEL);
mAwesomeValidation.setContext(this);  // mandatory for UNDERLABEL style

D. TEXT_INPUT_LAYOUT Style Type: This style is used with text_input_layout to show error message in Within text_input_layout. If you want to use this type of validation object, you can declare validation object as below.

AwesomeValidation mAwesomeValidation = new AwesomeValidation(TEXT_INPUT_LAYOUT);
1.3.2 Add required validations

The next step is to add the validation we want to be validated. We are just showing an example how will you add the validation. You can add other validation similarly.
To add any validation, you just need to call addValidation method. For example,

awesomeValidation.addValidation(this, R.id.etName, RegexTemplate.NOT_EMPTY, R.string.invalid_name);

Here, we have called the addValidation method and passed context, id of the view in which validation is applied, regex to validate and the message to show if validation is unsuccessful.
Similarly, you can add other validation as well. I have covered different types of validation you may need. For example, I have shown how to validation email, confirm email field, password, confirm password field etc.

awesomeValidation.addValidation(this, R.id.etName, RegexTemplate.NOT_EMPTY, R.string.invalid_name);
awesomeValidation.addValidation(this, R.id.etEmail, Patterns.EMAIL_ADDRESS, R.string.invalid_email);
awesomeValidation.addValidation(this, R.id.etConfirmEmail, R.id.etEmail, R.string.invalid_confirm_email);

String regexPassword = ".{8,}";
awesomeValidation.addValidation(this, R.id.etPassword, regexPassword, R.string.invalid_password);
awesomeValidation.addValidation(this, R.id.etConfirmPassword, R.id.etPassword, R.string.invalid_confirm_password);

awesomeValidation.addValidation(this, R.id.etPhone, "^[+]?[0-9]{10,13}$", R.string.invalid_phone);
awesomeValidation.addValidation(this, R.id.etAge, Range.closed(12, 60), R.string.invalid_age);
1.3.3 Trigger the validation to validate

Most of the hectic work is done now. The next step is to trigger the validation to validate the fields which you want to validate. To validate, you just need to call awesomeValidation.validate(). If there is some error in validation, you will get error message according to the type of style you have use. i.e. if you have used BAISC style, error message will be shown one by one. If you have used COLORATION style, incorrect inputs will be highlighted.

It’s better to trigger the validation when you want to submit the form. On click of Sumit button, you call awesomeValidation.validate(). This way you can validate the form just before submitting it to the server.

1.4. Final MainActivity.java code

After applying validation, finally our MainActivity class would look like below.
MainActivity.java

package com.tutorialwing.formvalidationawesomelibrary;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.utility.RegexTemplate;
import com.google.common.collect.Range;

import static com.basgeekball.awesomevalidation.ValidationStyle.UNDERLABEL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

	private EditText name;

	private EditText email;
	private EditText confirmEmail;

	private EditText password;
	private EditText confirmPassword;

	private EditText phone;
	private EditText age;

	private Button submit;

	private AwesomeValidation awesomeValidation;

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

		awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);

//// or
//		awesomeValidation = new AwesomeValidation(COLORATION);
//		awesomeValidation.setColor(Color.YELLOW);  // optional, default color is RED if not set
//// or
//		awesomeValidation = new AwesomeValidation(UNDERLABEL);
//		awesomeValidation.setContext(this);  // mandatory for UNDERLABEL style
//// or
//		AwesomeValidation mAwesomeValidation = new AwesomeValidation(TEXT_INPUT_LAYOUT);

		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);
		age = (EditText) findViewById(R.id.etAge);

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

		addValidationToViews();
	}

	private void addValidationToViews() {

		awesomeValidation.addValidation(this, R.id.etName, RegexTemplate.NOT_EMPTY, R.string.invalid_name);

		awesomeValidation.addValidation(this, R.id.etEmail, Patterns.EMAIL_ADDRESS, R.string.invalid_email);
		awesomeValidation.addValidation(this, R.id.etConfirmEmail, R.id.etEmail, R.string.invalid_confirm_email);

		String regexPassword = ".{8,}";
		awesomeValidation.addValidation(this, R.id.etPassword, regexPassword, R.string.invalid_password);
		awesomeValidation.addValidation(this, R.id.etConfirmPassword, R.id.etPassword, R.string.invalid_confirm_password);

		awesomeValidation.addValidation(this, R.id.etPhone, "^[+]?[0-9]{10,13}$", R.string.invalid_phone);
		awesomeValidation.addValidation(this, R.id.etAge, Range.closed(12, 60), R.string.invalid_age);
	}

	private void submitForm() {
		// Validate the form...
		if (awesomeValidation.validate()) {
			// Here, we are sure that form is successfully validated. So, do your stuffs now...
			Toast.makeText(this, "Form Validated Successfully", Toast.LENGTH_LONG).show();
		}
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.submit:
				submitForm();
				break;
		}
	}
}



Output

If you run the application, you will get output as given above. If you have any questions or got some problems while following this tutorial, you can download the source code as well. Source code link is already given above.

Conclusion

Android AwesomeValidation library is an easy to configure and use for Form Validation in Android. You just need to add some few lines to code and you are done. You will get output as desired. However, There is also another popular library(Saripaar Library) that can be used for form validation. You can use either one as per your need. Both libraries have some advantages and dis-advantages. So, which one to use depends on your need.

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.

  • unknown

    awesomeValidation.addValidation(this, R.id.etCpassword, R.id.etPassword, R.string.confirmpassworderror);
    I am getting error to this line that “cannot resolve method….”
    ???

    • At my end, i am not getting this error. Please verify following things
      1. Which version of awesomeValidation you are using? it should be same as what i am using in this tutorial.
      2. Did you press Sync after adding gradle?
      3. Are you using it in Activity? I have used “this” because the method is being used in activity.
      Note: You may download source code from given link.