Android – Validate email address

By -

Problem: How to validate email address in android?
Solution:

EmailValidationActivity.java

package com.technotalkative.emailvalidation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class EmailValidationActivity extends Activity {
    /** Called when the activity is first created. */

	EditText editTextEmail;
	String strEmailAddress;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    }

    String regEx =
    	"^(([w-]+.)+[w-]+|([a-zA-Z]{1}|[w-]{2,}))@"
    	    +"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9]).([0-1]?"
    	    +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])."
    	    +"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9]).([0-1]?"
    	    +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
    	    +"([a-zA-Z]+[w-]+.)+[a-zA-Z]{2,4})$";

    public void btnValidateEmailAddress(View v)
    {
    	strEmailAddress = editTextEmail.getText().toString().trim();

        Matcher matcherObj = Pattern.compile(regEx).matcher(strEmailAddress);

        if (matcherObj.matches()) {
        	Toast.makeText(v.getContext(), strEmailAddress+" is valid", Toast.LENGTH_SHORT).show();
        } else {
        	Toast.makeText(v.getContext(), strEmailAddress+" is InValid", Toast.LENGTH_SHORT).show();
        }
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <EditText
    	android:layout_height="100dp"
    	android:layout_width="match_parent"
    	android:id="@+id/editTextEmail"
    	android:inputType="textEmailAddress"
    	android:gravity="top">
    </EditText>

    <Button
    	android:layout_height="wrap_content"
    	android:layout_width="match_parent"
    	android:text="Validate Email address"
    	android:onClick="btnValidateEmailAddress"
    	android:id="@+id/btnValidateEmail">
    </Button>
</LinearLayout>

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

Loading Facebook Comments ...
Loading Disqus Comments ...