What is the best way to validate an email on Android?
I am trying to make a form in android in which one of the fields is a email and I wanted to know if there is any way for it to automatically check if the entered email is correct and instead show something like what the following image shows:
The field of the email I have specified as follows:
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/letraAzul"
android:inputType="textEmailAddress"
android:textSize="@dimen/texto_letra"
android:hint="Email"/>
Where android:inputType="textEmailAddress"
is only responsible for displaying a keyboard for the email introduction as the documentation says.
If there is no automatic way to do the check, what would be the best way to check that the email is correct?
Use:
android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
- a regular expression of type
"^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"
(which expression accepts more types of emails?) - other way
Does anyone know how to do this or have any examples or documentation that I can use?
Greetings
2 answers
You can use the Class pattern
private boolean validarEmail(String email) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();
}
As you can see we create an email_address pattern and check with the method matcher
if the email is correct.
if (!validarEmail("[email protected]")){
miEditText.setError("Email no válido")
}
If you just want to verify that the email is well formed, the Pattern
class is useful.
If you want to know if the email exists, is valid and is not a disposable orspamtrap mail the only effective way is to use an external service to validate email. There are quite a few providers, almost all through an API with which you can make a REST call, and it returns the result of the email validation.
//Llamada API validar email verificaremails.com
$email = "[email protected]";
$key = "your_api_key";
$url = "https://app.verificaremails.com/api/verifyEmail?secret=".$key."&email=".$email;