Open In App

Implement Email Validator in Android

Last Updated : 16 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: EditText widget in Android using Java with Examples

Email validation is required to inform the user that the Email entered by the user is not in a valid format. If the user has not entered the Email in the wrong format then the error filed is to be given for the EditText. In this article, it’s been discussed how to implement the Email validator in Android step by step. Have a look at the following image to get an idea of what’s been discussed in this article.


Steps to Implement the Email Validator in Android

Step 1: Create an empty activity project

Application Directory Structure

struct


Step 2: Add necessary resources

  • Download the image of email icon from here, and paste it inside your app > res > drawable folder.
  • You can see in the application directory structure an ’email.png’ present. If you see it, you have successfully added the image in your project.
  • If you don’t know how to add images inside the android application, refer this article: How to add images to Drawable folder in android.

Step 2: Working with the activity_main.xml file

  • In the main layout of the application, only two of the widgets are implemented. One is the Email EditText field and one Button which when clicked the entered email is to be checked.
  • Invoke the following code in the activity_main.xml file to implement the UI layout.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">

    <!--EditText which takes input
        as Email from the user-->
    <EditText
        android:id="@+id/emailField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="16dp"
        android:drawableStart="@drawable/email"
        android:drawablePadding="12dp"
        android:hint="Email" />

    <!--Button which when clicked validates
        the entered email is valid or not-->
    <Button
        android:id="@+id/validateButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/emailField"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:backgroundTint="@color/black"
        android:text="VALIDATE"
        android:textColor="@android:color/white" />

</RelativeLayout>

Output UI:

email


Step 3: Working with the MainActivity.java file

  • In this case, the pattern EMAIL_ADDRESS is used for demonstration purposes.
  • However, there are 5 more patterns to get validate the input from the user. Those are:

DOMAIN_NAME, IP_ADDRESS, PHONE, TOP_LEVEL_DOMAIN, WEB_URL.

  • Refer to the Patterns for more information about the predefined patterns in Android.
  • Invoke the following code inside the MainActivity.java file to implement the Email Validator in this case. Comments are added for a better understanding.
Java
package com.ishaanbhela.myapplication;

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

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

    // EditText filed for Email
    EditText etMail;

    // Button to validate the Email address
    Button bValidate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        etMail = findViewById(R.id.emailField);
        bValidate = findViewById(R.id.validateButton);

        // handle the VALIDATE button to show the toast
        // message whether the entered email is valid or not
        bValidate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emailValidator(etMail);
            }
        });
    }

    // the function which triggered when the VALIDATE button is clicked
    // which validates the email address entered by the user
    public void emailValidator(EditText etMail) {

        // extract the entered data from the EditText
        String emailToText = etMail.getText().toString();

        // Android offers the inbuilt patterns which the entered
        // data from the EditText field needs to be compared with
        // In this case the entered data needs to compared with
        // the EMAIL_ADDRESS, which is implemented same below
        if (!emailToText.isEmpty() && Patterns.EMAIL_ADDRESS.matcher(emailToText).matches()) {
            Toast.makeText(this, "Email Verified !", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Enter valid Email address !", Toast.LENGTH_SHORT).show();
        }
    }
}
Kotlin
package com.ishaanbhela.myapplication

import android.os.Bundle
import android.util.Patterns
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {

    private lateinit var myeditText: EditText
    private lateinit var email: String
    private lateinit var validate: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        myeditText = findViewById(R.id.emailField)
        email = myeditText.text.toString().trim()
        validate = findViewById(R.id.validateButton)

        // Setting onClick listener on Validate button to check if email pattern entered by user is correct or not.
        validate.setOnClickListener{
            check()
        }
    }
	
    // the function which triggered when the VALIDATE button is clicked
    // which validates the email address entered by the user
    private fun check() {
        // Getting the user input
        val text1 = myeditText.text

        if(text1.isEmpty()) // check if user have not entered then ask for enter
        {
            Toast.makeText(this@MainActivity,"enter your email id",Toast.LENGTH_LONG).show()
        }
        else
        {
          	// Android offers the inbuilt patterns which the entered
        	// data from the EditText field needs to be compared with
        	// In this case the entered data needs to compared with
        	// the EMAIL_ADDRESS, which is implemented same below
            if (Patterns.EMAIL_ADDRESS.matcher(text1).matches()) { // using EMAIL_ADREES matcher
                Toast.makeText(this@MainActivity, "Email Verified", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(this@MainActivity, "Enter valid Email address !", Toast.LENGTH_LONG).show()
            }
        }
    }
}

Output: Run on Emulator


Access the source code Here: Implement Email Validator in Android




Next Article

Similar Reads