Wed. May 1st, 2024

Validating EditText input in Android is a common task to ensure that the user enters the correct type of data. This can include checking for empty fields, validating email addresses, enforcing a certain length, or ensuring numeric input. Here’s a basic guide on how to perform EditText validations in Android:

1. Empty Field Validation:

  • Check if the EditText is empty when the user submits the form.
EditText editText = findViewById(R.id.editText);
String input = editText.getText().toString().trim();

if (input.isEmpty()) {
    // Show an error message, the field is empty
    editText.setError("Field cannot be empty");
} else {
    // Continue processing the input
}

Email Validation:

  • Use a regular expression to validate the email format.
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

if (!input.matches(emailPattern)) {
    // Show an error message, invalid email format
    editText.setError("Invalid email address");
} else {
    // Continue processing the input
}

Numeric Validation:

  • Ensure that the input is a valid numeric value.
if (!TextUtils.isDigitsOnly(input)) {
    // Show an error message, non-numeric input
    editText.setError("Please enter a numeric value");
} else {
    // Continue processing the input
}

Password Validation:

  • Implement password validation, such as checking for a minimum length
int minLength = 6;

if (input.length() < minLength) {
    // Show an error message, password too short
    editText.setError("Password must be at least " + minLength + " characters");
} else {
    // Continue processing the input
}

Custom Validation:

  • Implement custom validation based on your specific requirements.
// Example: Check if the input contains a specific substring
String requiredSubstring = "android";

if (!input.contains(requiredSubstring)) {
    // Show an error message, required substring not found
    editText.setError("Input must contain '" + requiredSubstring + "'");
} else {
    // Continue processing the input
}

Clearing Error:

  • Clear the error when the user corrects the input.

MainActivity.Java

editText.setError(null);
package com.androindian.validations;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    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) {
                    Toast.makeText(MainActivity.this,"Valid",Toast.LENGTH_LONG).show();
                }
            }
        });

        // 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;
    }
}

activity_main.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"
             />

        <Button
            android:id="@+id/proceedButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"

            android:text="PROCEED"
            android:textColor="@android:color/white"
            tools:ignore="ButtonStyle" />

    </LinearLayout>
</LinearLayout>

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

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