How to validate email in android

Email validation is an important functionality in all software application, Most of the application will use email as the unique way identifying users registered in their application , so it is important to validate email which the user is providing. In this tutorial we will learn how to validate an email in android.

Add the following function to your class file which will return boolean value.

public boolean isValidEmail(CharSequence email) {
if (TextUtils.isEmpty(email)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}

Now add the following If Loop in the action which you want to check the email validation.

if(isValidEmail("email to be validated")){

Toast.makeText(getApplicationContext(),"Email is valid",Toast.LENGTH_SHORT).show();
}else {

Toast.makeText(getApplicationContext(),"Email is not valid",Toast.LENGTH_SHORT).show();

}

Example

Let us see a small example of email validation in android.

Add the Following code to your layout, layout will contain an EditText to enter email address and a Button to do validation

<EditText
android:id="@+id/ed_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>

<Button
android:id="@+id/btn_validate_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Email validation"
android:background="@color/colorPrimary"
android:textColor="#FFFFFF"/>

Now add the following code to your activity class file

public class EmailValidate extends AppCompatActivity {


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

Button btn_validate_email = (Button) findViewById(R.id.btn_validate_email);
final EditText ed_email = (EditText) findViewById(R.id.ed_email);
btn_validate_email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

if(isValidEmail(ed_email.getText().toString())){

Toast.makeText(getApplicationContext(),"Email is valid",Toast.LENGTH_SHORT).show();
}else {

Toast.makeText(getApplicationContext(),"Email is not valid",Toast.LENGTH_SHORT).show();

}

}
});

}

public boolean isValidEmail(CharSequence email) {
if (TextUtils.isEmpty(email)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}
}

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *