Implement Form Validation (Error to EditText) in Android - GeeksforGeeks

08 Oct, 2021
In many of the already existing Android applications when it comes to the forms, where it includes user details. If the user enters the wrong information to the text fields or if the user leaves the text fields without filling it, there is a need to provide certain alert information to the TextFields which are unfilled and which contain the wrong information. So in this article, it’s been discussed step by step how to give the error texts to the user. Have a look at the following image to get an idea about what has to implement in this discussion. Note that we are going to implement this project using the Java language. 
In this discussion, two sample activities are taken for demonstration purposes, because in the first activity the text fields are implemented. If all the data entered in the text fields match the requirements then the user should proceed to the next activity.
Step 1: Create an empty activity project
Create an empty activity Android Studio project. And select the programming language as JAVA.
Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity android studio project.
Step 2: Working with the activity_main.xml
Here in this case for demonstration purposes, only four text fields are implemented those are, First Name, Last Name, Email, and Password.
Invoke the following code inside the activity_main.xml file.
XML
<?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:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity"    tools:ignore="HardcodedText">     <EditText        android:id="@+id/firstName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="16dp"        android:layout_marginTop="16dp"        android:layout_marginEnd="16dp"        android:hint="First Name"        android:inputType="text" />     <EditText        android:id="@+id/lastName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="16dp"        android:layout_marginTop="16dp"        android:layout_marginEnd="16dp"        android:hint="Last Name"        android:inputType="text" />     <EditText        android:id="@+id/email"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="16dp"        android:layout_marginTop="16dp"        android:layout_marginEnd="16dp"        android:hint="Email"        android:inputType="textEmailAddress" />     <EditText        android:id="@+id/password"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="16dp"        android:layout_marginTop="16dp"        android:layout_marginEnd="16dp"        android:hint="Password"        android:inputType="textPassword" />     <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="8dp"        android:gravity="end"        android:orientation="horizontal">         <Button            android:id="@+id/cancelButton"            style="@style/Widget.AppCompat.Button.Borderless"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginEnd="4dp"            android:text="CANCEL"            android:textColor="@color/colorPrimary" />         <Button            android:id="@+id/proceedButton"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginEnd="16dp"            android:backgroundTint="@color/colorPrimary"            android:text="PROCEED"            android:textColor="@android:color/white"            tools:ignore="ButtonStyle" />     </LinearLayout></LinearLayout>
  
 
Step 3: Create another empty activity
 
Create another empty activity with activity_main2.xml and invoke the following code, which contains a simple text “Activity 2” to avoid confusion.
The user should proceed to this activity, only when the user enters the data properly in the text fields given in the first activity.
 
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity2"    tools:ignore="HardcodedText">     <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="ACTIVITY 2"        android:textSize="18sp" /> </RelativeLayout>
  
Step 4: Working with the MainActivity.java file
 
Here for the instance of the EditText class, setError() is to be called.
When the data filled in the text filed is wrong ->
// this gives error message to particular text field  
// which contains the wrong data.
editText1.setError(“Error message”); 
    
When user data is corrected by the user ->
 // There is no need to give the error message when the user
 // corrects wrongly entered text field.
editText1.setError(null);
Invoke the following code. Comments are added for better understanding.
 
Java
import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText; public class MainActivity extends AppCompatActivity {     // two buttons    Button bCancel, bProceed;     // four text fields    EditText etFirstName, etLastName, etEmail, etPassword;     // one boolean variable to check whether all the text fields      // are filled by the user, properly or not.    boolean isAllFieldsChecked = false;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);         // register buttons with their proper IDs.        bProceed = findViewById(R.id.proceedButton);        bCancel = findViewById(R.id.cancelButton);         // register all the EditText fields with their IDs.        etFirstName = findViewById(R.id.firstName);        etLastName = findViewById(R.id.lastName);        etEmail = findViewById(R.id.email);        etPassword = findViewById(R.id.password);         // handle the PROCEED button        bProceed.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                 // store the returned value of the dedicated function which checks                // whether the entered data is valid or if any fields are left blank.                isAllFieldsChecked = CheckAllFields();                 // the boolean variable turns to be true then                  // only the user must be proceed to the activity2                if (isAllFieldsChecked) {                    Intent i = new Intent(MainActivity.this, MainActivity2.class);                    startActivity(i);                }            }        });         // if user presses the cancel button then close the          // application or the particular activity.        bCancel.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                MainActivity.this.finish();                System.exit(0);            }        });    }     // function which checks all the text fields      // are filled or not by the user.    // when user clicks on the PROCEED button      // this function is triggered.    private boolean CheckAllFields() {        if (etFirstName.length() == 0) {            etFirstName.setError("This field is required");            return false;        }         if (etLastName.length() == 0) {            etLastName.setError("This field is required");            return false;        }         if (etEmail.length() == 0) {            etEmail.setError("Email is required");            return false;        }         if (etPassword.length() == 0) {            etPassword.setError("Password is required");            return false;        } else if (etPassword.length() < 8) {            etPassword.setError("Password must be minimum 8 characters");            return false;        }           // after all validation return true.        return true;    }}
  
 
sooda367
gulshankumarar231
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Services in Android with Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples