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.
Table of Contents
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.
- 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.
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 |
<?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 2 3 |
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.
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 |
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 11 12 |
<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.
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 77 78 |
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.- Activity Context, we used this to pass the current activity context.
- Resource id of EditText in which we want to add validation, we used R.id.viewid
- Regex String for adding validation, you can use Regex for more kind of validations
- 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.
- 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 🙂