Android Validating Email EditText sample example methods tutorial

By | October 5, 2015

In this article we will see different methods to validate email address entered through EditText using android layout xml file. Email validation is useful in android because we need to send the email to server for registering a new account or for any other purpose.

If we validate the email in the android app itself then we won’t need to validate it at the server side.

Given below are some of the sample methods to validate the email address in Android:

Method-1) Following works for android 2.2 onwards

public final static boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

Method-2) Using Regular Expressions and adding the validation to textChangeListener of EditText:

EdiText emailValidate;
String email = emailValidate.getEditableText().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 
    } 
}); 

Method-3)

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;
}

Method-4)

 if (!emailRegistration.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+")) {

                            edttextEmail.setError("Invalid Email Address");

                        }

You can use any of the above methods to validate email address entered by your android app user in EditText of android layout file.

14,597 total views, 1 views today

(Visited 11,819 times, 1 visits today)