Hello folks, so in this article I am going to discuss about How to implement Android TextInputLayout validation using TextWatcher, How to validate email address using TextWatcher in android, how to create TextWatcher class, How to use TextInputLayout and TextInputEditText and get value in android and email validation android example .

In the today’s technical environment email validation, phone number validation is very useful to implement our business logic’s in android for example to register a new account, to send an email etc.

So here we use TextInputLayout, TextInputEditText and TextWatcher interface to implement validation on email addresses, phone number etc .

TextWatcher :

TextWatcher interface is used to keep watch on the content of a input text field while entering data into it. We can keep track of each character of input text field or TextInputEditText and can perform different operations on it .

TextWatcher is like an eye on user inputs and notify early instead of waiting until user press the submit button manually.

TextWatcher provides three different methods to perform different operations on input text field .

  • afterTextChanged(Editable editable) :- This method is called to notify you that the text has been changed or after changed made over input text field .
  • beforeTextChanged(CharSequence charsequence, int start, int count, int after) :- This method is called to notify you that, within charsequence, the count characters beginning at start are about to be replaced by new text with length after. or It is called before making any change over input text field .
  • onTextChanged(CharSequence charsequence, int start, int before, int count) :- This method is called to notify you that, within charsequence, the count characters beginning at start have just replaced old text that had length before. or It is called while making any change over input text field .

1. Create a New Project :

Create a new project in Android Studio from File > New Project and select Empty Activity from templates to create an email and password validation in android using TextWatcher .

2. Implement design support library :

Implement design support library inside your project build.gradle file .

implementation'com.android.support:design:28.0.0'

Try to add the latest version of the Design support library. Once that’s done, save the file and perform a Gradle sync.

Also read :-

3. Add a TextInputLayout and TextInputEditText :

Add a TextInputLayout and TextInputEditText to your activity_main.xml or xml layout file

<android.support.design.widget.TextInputLayout
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/pass"
        android:layout_margin="10dp">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:maxLines="1"
            android:hint="Enter email address"
            android:imeOptions="actionNext"
            android:lines="1"
            android:maxLength="10"
            android:singleLine="true"/>

    </android.support.design.widget.TextInputLayout>

Now open res -> layout -> activity_main.xml or xml layout file and just implement the following xml code .

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/pass"
        android:layout_margin="10dp">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:maxLines="1"
            android:hint="Enter email address"
            android:imeOptions="actionNext"
            android:lines="1"
            android:maxLength="10"
            android:singleLine="true"/>

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/submit"
        android:layout_margin="10dp">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:maxLines="1"
            android:hint="Enter your password"
            android:imeOptions="actionNext"
            android:lines="1"
            android:singleLine="true"/>

    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="10dp"
        android:text="Submit"/>

</RelativeLayout>

4. Implement custom TextWatcher sub class inside MainActivity.java for email and password validation :

Now we create a custom TextWatcher sub class inside MainActivity.java to keep track of each character of input text fields .

private class ValidationTextWatcher implements TextWatcher {

        private View view;

        private ValidationTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {
                case R.id.password:
                    validatePassword();
                    break;
                case R.id.editText:
                    validateEmail();
                    break;
            }
        }
    }

5. Open your MainActivity.java and add the following code :

Now create an instance of ValidationTextWatcher class and implement addTextChangedListener( ) to input fields or just implement the following code .

package net.technxt.textwatcher_validation;

import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    TextInputLayout pass, email;
    TextInputEditText password, editText;

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

        Button submit = findViewById(R.id.submit);

        pass = (TextInputLayout)findViewById(R.id.pass);
        email = (TextInputLayout)findViewById(R.id.email);

        password = (TextInputEditText) findViewById(R.id.password);
        editText = (TextInputEditText) findViewById(R.id.editText);


        password.addTextChangedListener(new ValidationTextWatcher(password));
        editText.addTextChangedListener(new ValidationTextWatcher(editText));


        // Capture button clicks
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {

                if (!validatePassword()) {
                    return;
                }
                if (!validateEmail()) {
                    return;
                }

            }
        });

    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private boolean validatePassword() {
        if (password.getText().toString().trim().isEmpty()) {
            pass.setError("Password is required");
            requestFocus(password);
            return false;
        }else if(password.getText().toString().length() < 6){
            pass.setError("Password can't be less than 6 digit");
            requestFocus(password);
            return false;
        }
        else {
            pass.setErrorEnabled(false);
        }
        return true;
    }

    private boolean validateEmail() {
        if (editText.getText().toString().trim().isEmpty()) {
            email.setErrorEnabled(false);
        } else {
            String emailId = editText.getText().toString();
            Boolean  isValid = android.util.Patterns.EMAIL_ADDRESS.matcher(emailId).matches();
            if (!isValid) {
                email.setError("Invalid Email address, ex: abc@example.com");
                requestFocus(editText);
                return false;
            } else {
                email.setErrorEnabled(false);
            }
        }
        return true;
    }

    private class ValidationTextWatcher implements TextWatcher {

        private View view;

        private ValidationTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {
                case R.id.password:
                    validatePassword();
                    break;
                case R.id.editText:
                    validateEmail();
                    break;
            }
        }
    }

}

Now run the project/app to test input text Validation in android app through android device or any Emulator .

%d bloggers like this: