Android10/1/2020

How to Validate Email and Password in Android Using Regex

Form validation is an important part of modern Android application development.

Applications commonly validate:

  • Email addresses
  • Usernames
  • Passwords
  • Phone numbers

Proper client-side validation improves user experience, reduces invalid API requests, and helps maintain better data quality.

In this tutorial, we will learn how to validate email addresses and passwords in Android using Regular Expressions (Regex).


What Is Regex?

Regex (Regular Expression) is a pattern matching technique used to validate and process text data.

Developers use regex for:

  • Email validation
  • Password rules
  • Phone number formatting
  • Input filtering

What We Will Build

In this Android example, we will:

  • Validate email format
  • Validate username length
  • Validate strong passwords
  • Display error messages using Material TextInputLayout

Step 1 — Add Material Design Dependency

Open your build.gradle file and add:


implementation 'com.google.android.material:material:1.11.0'

Then sync the Gradle project.


Step 2 — Create Layout File

Create the UI inside activity_main.xml.


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/text_input_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            android:inputType="textEmailAddress"/>

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/text_input_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:counterEnabled="true"
        app:counterMaxLength="15">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Username"/>

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/text_input_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:endIconMode="password_toggle">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:inputType="textPassword"/>

    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/button_confirm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Confirm"/>

</LinearLayout>

Step 3 — Implement Validation Logic

Open MainActivity.java and add the following code:


package com.example.validationapp;

import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputLayout;

import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private static final Pattern PASSWORD_PATTERN =
            Pattern.compile("^" +
                    "(?=.*[a-zA-Z])" +
                    "(?=.*[@#$%^&+=])" +
                    "(?=\\\\S+$)" +
                    ".{6,}" +
                    "$");

    private TextInputLayout textInputEmail;
    private TextInputLayout textInputUsername;
    private TextInputLayout textInputPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textInputEmail =
                findViewById(R.id.text_input_email);

        textInputUsername =
                findViewById(R.id.text_input_username);

        textInputPassword =
                findViewById(R.id.text_input_password);

        Button buttonConfirm =
                findViewById(R.id.button_confirm);

        buttonConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmInput();
            }
        });
    }

    private boolean validateEmail() {

        String emailInput =
                textInputEmail.getEditText()
                        .getText()
                        .toString()
                        .trim();

        if (emailInput.isEmpty()) {

            textInputEmail.setError(
                    "Field can't be empty"
            );

            return false;

        } else if (!Patterns.EMAIL_ADDRESS
                .matcher(emailInput)
                .matches()) {

            textInputEmail.setError(
                    "Please enter a valid email"
            );

            return false;

        } else {

            textInputEmail.setError(null);

            return true;
        }
    }

    private boolean validateUsername() {

        String usernameInput =
                textInputUsername.getEditText()
                        .getText()
                        .toString()
                        .trim();

        if (usernameInput.isEmpty()) {

            textInputUsername.setError(
                    "Field can't be empty"
            );

            return false;

        } else if (usernameInput.length() > 15) {

            textInputUsername.setError(
                    "Username too long"
            );

            return false;

        } else {

            textInputUsername.setError(null);

            return true;
        }
    }

    private boolean validatePassword() {

        String passwordInput =
                textInputPassword.getEditText()
                        .getText()
                        .toString()
                        .trim();

        if (passwordInput.isEmpty()) {

            textInputPassword.setError(
                    "Field can't be empty"
            );

            return false;

        } else if (!PASSWORD_PATTERN
                .matcher(passwordInput)
                .matches()) {

            textInputPassword.setError(
                    "Password too weak"
            );

            return false;

        } else {

            textInputPassword.setError(null);

            return true;
        }
    }

    private void confirmInput() {

        if (!validateEmail()
                | !validateUsername()
                | !validatePassword()) {

            return;
        }

        Toast.makeText(
                this,
                "Validation Successful",
                Toast.LENGTH_SHORT
        ).show();
    }
}

How Password Regex Works

The regex pattern checks:

  • At least one alphabet character
  • At least one special character
  • No whitespace
  • Minimum password length

Regex pattern used:


(?=.*[a-zA-Z])
(?=.*[@#$%^&+=])
(?=\\S+$)
.{6,}

How Email Validation Works

Android provides a built-in email validation pattern:


Patterns.EMAIL_ADDRESS.matcher(email).matches()

This helps validate whether the entered email follows standard email formatting.


Expected Output

After running the application:

  • Users can enter email, username, and password
  • Invalid fields display error messages
  • Valid inputs show success message

Common Validation Mistakes

1. Weak Password Rules

Weak passwords reduce application security.


2. Overly Strict Validation

Very strict regex rules may block legitimate user inputs.


3. Missing Server-Side Validation

Client-side validation improves UX, but backend validation is still required for security.


Modern Android Validation Improvements

Production Android applications should also consider:

  • Real-time validation
  • Kotlin implementation
  • ViewBinding
  • MVVM architecture
  • Server-side verification

FAQ

Why use regex for validation?

Regex helps developers validate text patterns efficiently.

Can regex validate all email addresses perfectly?

No. Regex can validate formatting, but complete email verification requires backend confirmation.

Should passwords be validated only on frontend?

No. Password validation should always happen on both frontend and backend.


Conclusion

Input validation is an important part of Android application development.

Using regex with Material TextInputLayout improves form validation, user experience, and application reliability.

Modern Android applications should combine client-side validation with secure backend verification for better security.


About the Author

Salil Jha is a Full Stack and Mobile Developer with experience in Android, React Native, scalable SaaS platforms, fintech applications, and developer tooling systems.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Deep Structural Diagnostics.

Mastering JSON is only the first step. Use our industrial-grade workbench to format, validate, and synthesize models for your production APIs.