Email Address Validation in Android on EditText

AndroidAndroid EdittextEmail Validation

Android Problem Overview


How can we perform Email Validation on edittext in android ? I have gone through google & SO but I didn't find out a simple way to validate it.

Android Solutions


Solution 1 - Android

Java:

public static boolean isValidEmail(CharSequence target) {
    return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
}

Kotlin:

fun CharSequence?.isValidEmail() = !isNullOrEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()

Edit: It will work On Android 2.2+ onwards !!

Edit: Added missing ;

Solution 2 - Android

To perform Email Validation we have many ways,but simple & easiest way are two methods.

1- Using EditText(....).addTextChangedListener which keeps triggering on every input in an EditText box i.e email_id is invalid or valid

/**
 * Email Validation ex:- [email protected]
*/


final EditText emailValidate = (EditText)findViewById(R.id.textMessage); 

final TextView textView = (TextView)findViewById(R.id.text); 

String email = emailValidate.getText().toString().trim();

String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

emailValidate .addTextChangedListener(new TextWatcher() { 
    public void afterTextChanged(Editable s) { 
        
    if (email.matches(emailPattern) && s.length() > 0)
        { 
            Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
            // or
            textView.setText("valid email");
        }
        else
        {
             Toast.makeText(getApplicationContext(),"Invalid email address",Toast.LENGTH_SHORT).show();
            //or
            textView.setText("invalid email");
        }
    } 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // other stuffs 
    } 
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    // other stuffs 
    } 
}); 

2- Simplest method using if-else condition. Take the EditText box string using getText() and compare with pattern provided for email. If pattern doesn't match or macthes, onClick of button toast a message. It ll not trigger on every input of an character in EditText box . simple example shown below.

final EditText emailValidate = (EditText)findViewById(R.id.textMessage); 

final TextView textView = (TextView)findViewById(R.id.text); 

String email = emailValidate.getText().toString().trim();

String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

// onClick of button perform this simplest code.
if (email.matches(emailPattern))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else 
{
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}

Solution 3 - Android

I did this way:

Add this method to check whether email address is valid or not:

private boolean isValidEmailId(String email){
	  
	return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
              + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
              + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
              + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
              + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
              + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
	 }

Now check with String of EditText:

if(isValidEmailId(edtEmailId.getText().toString().trim())){
  Toast.makeText(getApplicationContext(), "Valid Email Address.", Toast.LENGTH_SHORT).show();
}else{       
  Toast.makeText(getApplicationContext(), "InValid Email Address.", Toast.LENGTH_SHORT).show();
}

Done

Solution 4 - Android

Use this method for validating your email format. Pass email as string , it returns true if format is correct otherwise false.

/**
 * validate your email address format. [email protected]
 */
public boolean emailValidator(String email) 
{
	Pattern pattern;
	Matcher matcher;
	final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	pattern = Pattern.compile(EMAIL_PATTERN);
	matcher = pattern.matcher(email);
	return matcher.matches();
}

Solution 5 - Android

Try this:

if (!emailRegistration.matches("[a-zA-Z0-9._-]+@[a-z]+\.[a-z]+")) {
 editTextEmail.setError("Invalid Email Address");
}

Solution 6 - Android

public static boolean isEmailValid(String email) {
	boolean isValid = false;

	String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
	CharSequence inputStr = email;

	Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
	Matcher matcher = pattern.matcher(inputStr);
	if (matcher.matches()) {
		isValid = true;
	}
	return isValid;
}

Solution 7 - Android

Use this method to validate the EMAIL :-

 public static boolean isEditTextContainEmail(EditText argEditText) {
    
    		try {
    			Pattern pattern = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
    			Matcher matcher = pattern.matcher(argEditText.getText());
    			return matcher.matches();
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}

Let me know if you have any queries ?

Solution 8 - Android

try this

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}" +
	          ")+"
	      );
	

and in tne edit text

final String emailText = email.getText().toString();
EMAIL_ADDRESS_PATTERN.matcher(emailText).matches()
		

				

Solution 9 - Android

This is a sample method i created to validate email addresses, if the string parameter passed is a valid email address , it returns true, else false is returned.

private boolean validateEmailAddress(String emailAddress){
	String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";  
	   CharSequence inputStr = emailAddress;  
	   Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);  
	   Matcher matcher = pattern.matcher(inputStr);  
	   return matcher.matches();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRahul BaradiaView Question on Stackoverflow
Solution 1 - Androiduser1737884View Answer on Stackoverflow
Solution 2 - AndroidRahul BaradiaView Answer on Stackoverflow
Solution 3 - AndroidHiren PatelView Answer on Stackoverflow
Solution 4 - AndroidAkhilesh ManiView Answer on Stackoverflow
Solution 5 - AndroidJay ThakkarView Answer on Stackoverflow
Solution 6 - AndroidNagarjunaReddyView Answer on Stackoverflow
Solution 7 - AndroidGaurav AroraView Answer on Stackoverflow
Solution 8 - AndroidNaveen KumarView Answer on Stackoverflow
Solution 9 - AndroidAppMobiGurmeetView Answer on Stackoverflow