To learn how to validate an email address, we create a simple example.
Step 1: create new android project
Step 2: create the layout: res\layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.tutorialspots.emailvalidate.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TUTORIALSPOTS.COM" android:textColor="#FF0000" android:textSize="30dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:id="@+id/textView" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Enter your email address:" android:id="@+id/textView2" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:ems="15" android:id="@+id/editText" android:layout_below="@+id/textView2" android:layout_centerHorizontal="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Validate" android:id="@+id/button" android:onClick="validateEmail" android:layout_below="@+id/editText" android:layout_centerHorizontal="true" /> </RelativeLayout>
Step 3: file MainActivity.java
package com.tutorialspots.emailvalidate; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity { EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.editText); } public void validateEmail(View view){ String email = editText.getText().toString(); if(isValidEmail(email)){ Toast.makeText(view.getContext(), "Email is valid", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(view.getContext(), "Email is invalid", Toast.LENGTH_LONG).show(); } } public static boolean isValidEmail(String email) { String expression = "^[\\w\\.]+@([\\w]+\\.)+[A-Z]{2,7}$"; CharSequence inputString = email; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputString); if (matcher.matches()) { return true; } else{ return false; } } }
Step 4: run for test