Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I validate an e-mail address?

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 available. Are there any other libraries doing this which are included in Android already or would I have to use RegExp?

like image 427
znq Avatar asked Nov 30 '09 11:11

znq


2 Answers

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(); } 
like image 138
mindriot Avatar answered Oct 03 '22 17:10

mindriot


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(); } 
like image 36
Andrei Buneyeu Avatar answered Oct 03 '22 15:10

Andrei Buneyeu