How to Validate a Password using Regular Expressions in Android?
Last Updated :
11 Dec, 2020
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:
- MatchResult Interface
- Matcher class
- Pattern class
- PatternSyntaxException class

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'
Example
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 'com.google.android.material:material:1.0.0'
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.Â
XML
<resources>
<color name="colorPrimary">#0F9D58</color>
<color name="colorPrimaryDark">#16E37F</color>
<color name="colorAccent">#03DAC5</color>
</resources>
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
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<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/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true"
app:passwordToggleEnabled="true">
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="confirmInput"
android:text="Submit" />
</LinearLayout>
Step 4: Working with the MainActivity.java file
In the MainActivity.java 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 MainActivity.java file.
Java
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
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 {
// 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Referencing email and password
email = findViewById(R.id.email);
password = findViewById(R.id.password);
}
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 {
email.setError(null);
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 {
password.setError(null);
return true;
}
}
public void confirmInput(View v) {
if (!validateEmail() | !validatePassword()) {
return;
}
// 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
Similar Reads
How to validate an IP address using Regular Expressions in Java Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.Examples: Inpu
3 min read
How to validate ISIN using Regular Expressions ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
6 min read
How to Validate MICR Code using Regular Expression? MICR stands for Magnetic Ink Character Recognition. This technology provides transaction security, ensuring the correctness of bank cheques. MICR code makes cheque processing faster and safer. MICR Technology reduces cheque-related fraudulent activities. Structure of a Magnetic Ink Character Recogni
5 min read
How to validate a Username using Regular Expressions in Java Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions. A username is considered valid if all the following constraints are satisfied: The username consists of 6 to 30 characters inclusive. If the username consists of less than 6 or
3 min read
Regular Expressions to Validate Google Analytics Tracking Id Given some Google Analytics Tracking IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid Tracking Id are: It is an alphanumeric string i.e., containing digits (0-9), alphabets (A-Z), and a Special character hyphen(-).The hyphen will come in between the g
5 min read