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 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(); } } |