How should I validate an e-mail address?
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();
}
Next pattern is used in K-9 mail:
public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
You can use function
private boolean checkEmail(String email) {
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}
Since API 8 (android 2.2) there is a pattern: android.util.Patterns.EMAIL_ADDRESS http://developer.android.com/reference/android/util/Patterns.html
So you can use it to validate yourEmailString:
private boolean isValidEmail(String email) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();
}
returns true if the email is valid
UPD: This pattern source code is:
public static final Pattern EMAIL_ADDRESS
= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
refer to: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/util/Patterns.java
So you can build it yourself for compatibility with API < 8.