Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaImplement Form Validation (Error to EditText) in Android

Implement Form Validation (Error to EditText) in Android

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.

Form Validation in Android

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: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: 

Form Validation in Android

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: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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments