Implement Form Validation (Error to EditText) in Android
Last Updated :
01 Aug, 2024
Many of the already existing Android applications when it comes to the forms include user details. If the user enters the wrong information into the text fields or if the user leaves the text fields without filling them, 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.
Steps for Implementing form Validation in Android
Step 1: Create an empty activity 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>
Output UI:Â

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 field 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;
}
}
Kotlin
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;
class MainActivity : AppCompatActivity() {
// two buttons
var bCancel: Button? = null
var bProceed: Button? = null
// four text fields
var etFirstName: EditText? = null
var etLastName: EditText? = null
var etEmail: EditText? = null
var etPassword: EditText? = null
// one boolean variable to check whether all the text fields
// are filled by the user, properly or not.
var isAllFieldsChecked = false
override fun onCreate(savedInstanceState: Bundle?) {
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(object : OnClickListener() {
fun onClick(v: View?) {
// 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) {
val i = Intent(this@MainActivity, MainActivity2::class.java)
startActivity(i)
}
}
})
// if user presses the cancel button then close the
// application or the particular activity.
bCancel.setOnClickListener(object : OnClickListener() {
fun onClick(v: View?) {
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 fun CheckAllFields(): Boolean {
if (etFirstName!!.length() == 0) {
etFirstName!!.error = "This field is required"
return false
}
if (etLastName!!.length() == 0) {
etLastName!!.error = "This field is required"
return false
}
if (etEmail!!.length() == 0) {
etEmail!!.error = "Email is required"
return false
}
if (etPassword!!.length() == 0) {
etPassword!!.error = "Password is required"
return false
} else if (etPassword!!.length() < 8) {
etPassword!!.error = "Password must be minimum 8 characters"
return false
}
// after all validation return true.
return true
}
}
//This code is written by Ujjwal Kumar Bhardwaj
Output: Run on Emulator
Similar Reads
Implement Email Validator in Android
Prerequisite: EditText widget in Android using Java with Examples Email validation is required to inform the user that the Email entered by the user is not in a valid format. If the user has not entered the Email in the wrong format then the error filed is to be given for the EditText. In this artic
5 min read
EditText widget in Android with Example
Widget refers to the elements of the UI (User Interface) that helps user interacts with the Android App. EditText is one of many such widgets which can be used to retrieve text data from user. EditText refers to the widget that displays an empty text field in which a user can enter the required text
5 min read
How to Add Image on EditText in Android?
In Android, An EditText is an overlay over a TextView that makes it editable using text by invoking a soft keyboard in run time. It is generally implemented to collect text data from the user. EditText is most commonly used in forms that require users to fill in details and for passing a search quer
3 min read
How to Implement Dynamic TabLayout in Android?
In this article, we will learn about how to add Dynamic TabLayout with ViewPager in an app. TabLayout provides a horizontal layout to display tabs. Here we will be just specifying the number of tabs we want to have. WhatsApp, Facebook, etc are a very good example of TabLayout with ViewPager. A sampl
5 min read
Implement Phone Number Validator in Android
Phone validation is useful for users to check whether the number entered by the user is a valid number or not. If the user has entered the number is not valid then it will show a Toast message to re-enter the number. In this article, we are going to discuss how to implement the phone number validato
3 min read
How to Implement Country Code Picker in Android?
Country Code Picker (CCP) is an android library that helps users to select country codes (country phone codes) for telephonic forms. CCP provided a UI component that helps the user to select country codes, country flags, and many more in an android spinner. It gives well-designed looks to forms on t
3 min read
How to Set Restriction For URL in Android EditText?
In this article, we are going to set restrictions in our EditText for URL. Whenever we are creating any form and we want to get the portfolio website of the user or even if we want to restrict the user to write the only URL then we can use this feature. This enables a user to user to write URL only.
2 min read
How to Implement OTP View in Android?
An OTP View or PinView in android is a widget that allows users to enter their PIN, OTP, etc. They are generally used for two-factor authentication or phone number verification by OTP. A sample video is given below to get an idea about what we are going to do in this article. [video loading="lazy" m
2 min read
Material Design EditText in Android with Example
EditText is one of the important UI elements. Edittext refers to the widget that displays an empty text field in which a user can enter the required text and this text is further used inside the application. In this article it has been discussed to implement the special type of text fields, those ar
3 min read
How to Implement View Binding Inside Dialog in Android?
In android, View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views th
4 min read