What\'s a good technique for validating an e-mail address (e.g. from a user input field) in Android? org.apache.commons.validator.routines.EmailValidator doesn\'t seem to be
This is Android Studio suggestions:
public static boolean isEmailValid(String email) {
return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public boolean isValidEmail(String email)
{
boolean isValidEmail = false;
String emailExpression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(emailExpression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
isValidEmail = true;
}
return isValidEmail;
}
If you are using API 8 or above, you can use the readily available Patterns
class to validate email. Sample code:
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
By chance if you are even supporting API level less than 8, then you can simply copy the Patterns.java
file into your project and reference it. You can get the source code for Patterns.java
from this link
You could also use
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
If the email is not valid it will throw an AddressException.
Unfortunately Android doesn't support jndi-dns, but just to give you an idea of a more powerful email validation, you could use it to validate the email domain. Maybe an Android guru could help and show if there are similar alternatives... An example implementation with "regular" java is available here.
EDIT
I just realized that javax.mail isn't support neither... But this post shows a workaround.
Another option is the built in Patterns starting with API Level 8:
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Patterns viewable source
OR
One line solution from @AdamvandenHoven:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
The Linkify class has some pretty useful helper methods that might be relevant, including regular expressions designed to pick up phone numbers and email addresses and such:
http://developer.android.com/reference/android/text/util/Linkify.html