• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Email address validation

23tony

Well-Known Member
I'm wondering what others use to check if an email address is valid. I don't mean that it's an actual in-use address, just that it is correctly formatted.

I found a couple references that pointed me to javax.mail.InternetAddress and to Apache Commons - I'm not completely clear on how to get the Apache Commons one onto my system, and it looks like javax.mail isn't supported, at least not OOB for Studio 3.3.2 (it doesn't recognize the import).

Do you use something different? Or can someone help me get one of the prebuilt ones working?

Thanks in advance!
 
I'm wondering what others use to check if an email address is valid. I don't mean that it's an actual in-use address, just that it is correctly formatted.
The following has worked well for me to check email formatting. You only need the isValidEmail() method - the rest of the code is just showing how it can be used with an EditText.

Java:
EditText userEmail = findViewById(R.id.user_email);
String email = userEmail.getText().toString();

if (!isValidEmail(email)) {
    userEmail.setError("Invalid Email!");
    return;
}

private boolean isValidEmail(String email) {
    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 = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}
 
Back
Top Bottom