Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / Android Application Development / Android Form Validation Tutorial using AwesomeValidation Library

Android Form Validation Tutorial using AwesomeValidation Library

October 8, 2016 by Belal Khan 13 Comments

Today we will learn about Android Form Validation. In any app input validation is a very important thing to do. Input Validation eliminates the errors that can be done by user while giving inputs to our app. For example if we want to get the user’s email we can check the entered email is a valid email or not before storing it inside the database. So lets start our Android Form Validation tutorial.

Contents

  • 1 Creating a New Project
  • 2 Creating a Form
  • 3 Android Form Validation
    • 3.1 Adding AwesomeValidation Library
    • 3.2 Defining View Objects
    • 3.3 Defining Strings for Error Messages
    • 3.4 Validating Input Fields
    • 3.5 Testing the App
    • 3.6 Sharing is Caring:
    • 3.7 Related

Creating a New Project

  • The first step as always to create a new project.
  • So create a new Android Studio Project and come inside your activity_main.xml to design our form.

Creating a Form

  • Now to validate we need a form. So inside activity_main.xml create some input fields. I have designed the screen given below.
Android Form Validation

Android Form Validation

  • In the above screen we have 5 EditTexts and 1 Button. Now we will validate these fields for the connect input when the button is pressed. If you are facing trouble creating the EditTexts, you can copy the following xml code.

activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.androidvalidationexample.MainActivity">
 
    <EditText
        android:id="@+id/editTextName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName" />
 
    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Email"
        android:inputType="textPersonName" />
 
    <EditText
        android:id="@+id/editTextMobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Mobile Number"
        android:inputType="textEmailAddress" />
 
    <EditText
        android:id="@+id/editTextDob"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Date of Birth (DD/MM/YYYY)"
        android:inputType="date" />
 
    <EditText
        android:id="@+id/editTextAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Age"
        android:inputType="number" />
 
    <Button
        android:id="@+id/buttonSubmit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit" />
 
</LinearLayout>

Android Form Validation

Adding AwesomeValidation Library

  • So we are going to use AwesomeValidation. So first come inside app level build.gradle file and add the following line inside dependencies block.

1
compile 'com.basgeekball:awesome-validation:1.3'

  • Now after adding the above line sync your project.

Defining View Objects

  • Now first we need to define all the View Objects that is needed. So in this case we will define the objects inside MainActivity.java.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package net.simplifiedcoding.androidvalidationexample;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    //The view objects
    private EditText editTextName, editTextEmail, editTextMobile,
            editTextDob, editTextAge;
 
    private Button buttonSubmit;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //initializing view objects
        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextMobile = (EditText) findViewById(R.id.editTextMobile);
        editTextDob = (EditText) findViewById(R.id.editTextDob);
        editTextAge = (EditText) findViewById(R.id.editTextAge);
 
        buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
 
        buttonSubmit.setOnClickListener(this);
    }
 
    private void submitForm() {
        //first validate the form then move ahead    
    }
    
    @Override
    public void onClick(View view) {
        if (view == buttonSubmit) {
            submitForm();
        }
    }
}

Defining Strings for Error Messages

  • To display the error messages we need to define all the strings needed inside strings.xml file. So define the following strings inside strings.xml.

1
2
3
4
5
6
7
8
9
10
<resources>
    <string name="app_name">AndroidValidationExample</string>
 
    <string name="nameerror">Enter a valid name</string>
    <string name="emailerror">Enter a valid email</string>
    <string name="mobileerror">Enter a valid mobile</string>
    <string name="dateerror">Enter a valid date</string>
    <string name="ageerror">Enter a valid age</string>
 
</resources>

Validating Input Fields

  • To validate the input the modify the code as below.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package net.simplifiedcoding.androidvalidationexample;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.ValidationStyle;
import com.google.common.collect.Range;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    //The view objects
    private EditText editTextName, editTextEmail, editTextMobile,
            editTextDob, editTextAge;
 
    private Button buttonSubmit;
 
    //defining AwesomeValidation object
    private AwesomeValidation awesomeValidation;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //initializing awesomevalidation object
        /*
        * The library provides 3 types of validation
        * BASIC
        * COLORATION
        * UNDERLABEL
        * */
        awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);
 
        //initializing view objects
        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextMobile = (EditText) findViewById(R.id.editTextMobile);
        editTextDob = (EditText) findViewById(R.id.editTextDob);
        editTextAge = (EditText) findViewById(R.id.editTextAge);
 
        buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
 
 
        //adding validation to edittexts
        awesomeValidation.addValidation(this, R.id.editTextName, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);
        awesomeValidation.addValidation(this, R.id.editTextEmail, Patterns.EMAIL_ADDRESS, R.string.nameerror);
        awesomeValidation.addValidation(this, R.id.editTextMobile, "^[2-9]{2}[0-9]{8}$", R.string.nameerror);
        awesomeValidation.addValidation(this, R.id.editTextDob, "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$", R.string.nameerror);
        awesomeValidation.addValidation(this, R.id.editTextAge, Range.closed(13, 60), R.string.ageerror);
 
        buttonSubmit.setOnClickListener(this);
    }
 
    private void submitForm() {
        //first validate the form then move ahead
        //if this becomes true that means validation is successfull
        if (awesomeValidation.validate()) {
            Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
 
            //process the data further
        }
    }
 
    @Override
    public void onClick(View view) {
        if (view == buttonSubmit) {
            submitForm();
        }
    }
}

What we did?

  • First we defined an AwesomeValidation object.
  • We initialized the object with BASIC style, we have two more different style COLORATION and UNDERLABEL.
  • Then we added the validation to required EditTexts using addValidation() method with AwesomeValidation object.
    addValidation() : This method takes 4 arguments.

    1. Activity Context, we used this to pass the current activity context.
    2. Resource id of EditText in which we want to add validation, we used R.id.viewid
    3. Regex String for adding validation, you can use Regex for more kind of validations
    4. String resource id for error message to show the error if validation fails
  • Then in submitForm() method we are validating the inputs with validate() method. The method returns true or false, true if validation succeeds and false if validation fails.

Testing the App

  • Now you can run the app to test whether it is working or not.

android form validation example

  • You can see in the above screenshot it is working absolutely fine.

So thats all for this Android Form Validation Tutorial friends. Please share this post if you found it useful. And also don’t hesitate to leave your comments if you are facing any troubles. Thank You 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Application Development, Android Intermediate Tagged With: android edittext validation, android form validation, form validation android

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. Abdul Samad says

    October 20, 2016 at 9:34 am

    Cool, but in your activity_main.xml file, you gave inputType =”textEmailAddress” to the mobile number field. Is it a typo or deliberate?

    Reply
    • Belal Khan says

      October 21, 2016 at 6:32 am

      It will open the keyboard to enter email (you will find @ symbol in keyword directly) .. nothing else

      Reply
  2. Manish Kumar says

    November 13, 2016 at 3:18 am

    can you please video tutorial of this topic??

    Reply
  3. Amandi Nwankwo says

    November 27, 2016 at 8:05 pm

    Hello Mr Belal,
    Thank you for all you have been posting. i wish you more success in your endavour. Please i want to ask if you could post an article on chat messages for android using smack/xmmp with openfire server to send and receive chat messages. Thanks very much in advance.

    Reply
  4. srini says

    November 30, 2016 at 9:33 am

    password is essiential for signup please upload that tooo

    Reply
  5. frank says

    December 1, 2016 at 10:21 am

    how about if i want display error at TextInputLayout instead ?

    Reply
  6. Vinod Shinde says

    February 22, 2017 at 5:46 am

    Hello bilal, I’m new in android. I want ask one question that, How much reliable Awesome Validation. Can i get support in future if implemented in my application ?

    Reply
  7. Riya says

    March 2, 2017 at 1:24 pm

    hi belal,
    how to compare two EditText ? I wanna compare password and confirm password , so could u help me…

    Reply
    • shashikant says

      March 6, 2017 at 12:08 pm

      use equal method… common its easy

      Reply
  8. k pradeepkumar reddy says

    July 11, 2017 at 9:33 am

    Regex strings you have used are too complex to understand.

    Reply
  9. muthu says

    December 20, 2017 at 10:17 am

    please post the tutorial for fragment validation using awesome-validation library

    Reply
    • Belal Khan says

      December 22, 2017 at 2:15 pm

      It is for input validation I guess.. And can you please explain what is fragment validation?

      Reply
  10. Nitish says

    October 14, 2018 at 10:36 am

    Please Upload Login and Logout code on Shared Preference with regex validation

    Reply

Leave a Reply to Manish Kumar Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.