Open In App

How to Validate a Password using Regular Expressions in Android?

Last Updated : 11 Dec, 2020
Like Article

Regular Expression basically defines a search pattern, pattern matching, or string matching. It is present in java.util.regex package. Java Regex API provides 1 interface and 3 classes. They are the following:

  1. MatchResult Interface
  2. Matcher class
  3. Pattern class
  4. PatternSyntaxException class

Validate a Password using Regular Expressions in Android

Pattern p = Pattern.compile(“.e”); // represents single character

Matcher m = p.matcher(“geeks”);

boolean b = m.matches(); // the boolean value of ‘b’ is true as second character in geeks is ‘e’


In this example, we will validate email and password on the client-side which means that we don’t check that email-password are stored at some server and matches to it, instead, we compare the email-password to a predefined pattern. Note we are going to implement this project in Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Adding Dependencies

In order to use the design support library, we need to add its dependencies. Go to Gradle Scripts > build.gradle(Module:app) and add the following dependencies. After adding the dependency click on Sync Now.

implementation ‘’

Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. 


    <color name="colorPrimary">#0F9D58</color
    <color name="colorPrimaryDark">#16E37F</color
    <color name="colorAccent">#03DAC5</color

Step 3: Designing the layout file

In this step, we will design the layout for our application. Go to app > res > layout > activity_main.xml. In this layout, we have used TextInputLayout in order to add extra features to our EditText, such as spacing for error message below Views. Below is the code snippet is given for the activity_main.xml file.


<?xml version="1.0" encoding="utf-8"?>
            android:inputType="textEmailAddress" />
            android:inputType="textPassword" />
        android:text="Submit" />

Step 4: Working with the file

In the file we use the predefined pattern for Email validation and define our own pattern for password validation. For this, we have defined two methods ValidateEmail() and ValidatePassword(). ValidateEmail() method uses predefined email pattern .i.e., it must have ‘@’ and ‘.'(dot) in the input email. If the email fails to satisfy the condition it will display an error message “Please enter a valid email address”. In ValidatePassword(), we define our own pattern as:

private static final Pattern PASSWORD_PATTERN =

           Pattern.compile(“^” +

                   “(?=.*[@#$%^&+=])” +     // at least 1 special character

                   “(?=\\S+$)” +                     // no white spaces

                   “.{4,}” +                              // at least 4 characters


If the password fails to satisfy any of these conditions, an error message will be shown as “Password is too weak”.  If any of the field email or password is empty, it will display “Fields can not be empty”. If both email and password match the conditions, a toast message will be displayed which shows that input email and password. Below is the code snippet for the file.


import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Toast;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
    // defining our own password pattern
    private static final Pattern PASSWORD_PATTERN =
            Pattern.compile("^" +
                    "(?=.*[@#$%^&+=])" +     // at least 1 special character
                    "(?=\\S+$)" +            // no white spaces
                    ".{4,}" +                // at least 4 characters
    private TextInputLayout email;
    private TextInputLayout password;
    protected void onCreate(Bundle savedInstanceState) {
        // Referencing email and password
        email = findViewById(;
        password = findViewById(;
    private boolean validateEmail() {
        // Extract input from EditText
        String emailInput = email.getEditText().getText().toString().trim();
        // if the email input field is empty
        if (emailInput.isEmpty()) {
            email.setError("Field can not be empty");
            return false;
        // Matching the input email to a predefined email pattern
        else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
            email.setError("Please enter a valid email address");
            return false;
        } else {
            return true;
    private boolean validatePassword() {
        String passwordInput = password.getEditText().getText().toString().trim();
        // if password field is empty
        // it will display error message "Field can not be empty"
        if (passwordInput.isEmpty()) {
            password.setError("Field can not be empty");
            return false;
        // if password does not matches to the pattern
        // it will display an error message "Password is too weak"
        else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) {
            password.setError("Password is too weak");
            return false;
        } else {
            return true;
    public void confirmInput(View v) {
        if (!validateEmail() | !validatePassword()) {
        // if the email and password matches, a toast message 
        // with email and password is displayed
        String input = "Email: " + email.getEditText().getText().toString();
        input += "\n";
        input += "Password: " + password.getEditText().getText().toString();
        Toast.makeText(this, input, Toast.LENGTH_SHORT).show();

Output: Run On Emulator

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads