This code snippet shows how you can validate the format of an email address. If the email pattern is valid, there is no message.
Code Snippet
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
Button btn_validate;
EditText et_email;
String emailAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_validate = (Button) findViewById(R.id.btn_validate);
et_email = (EditText) findViewById(R.id.et_email);
btn_validate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
emailAddress = et_email.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches() | TextUtils.isEmpty(emailAddress)) {
et_email.setError("Invalid Email");
et_email.requestFocus();
}
}
});
}
}
XML Layout
<LinearLayout 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:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:text="@string/validate_email"
android:textSize="15sp" />
<EditText
android:id="@+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:hint="@string/enter_email_address"
android:inputType="textEmailAddress"
android:textSize="15sp" />
<Button
android:id="@+id/btn_validate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:text="@string/ok"
android:textSize="15sp" />
</LinearLayout>
Note: If in a smartphone the email error message does not display you can set this instead of a string value:
Html.fromHtml("<font color='black'>Invalid Email Format!</font>")