1

I've seen solutions here to validate whether an email address is formatted correctly, however I would like to check if an email address uses a specific domain such as "@gmail.com". The example I am referring to which validates email address format in general is:

public final static boolean isValidEmail(CharSequence target) {
  if (TextUtils.isEmpty(target)) {
    return false;
  } else {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
  }
}
Paradox
  • 4,602
  • 12
  • 44
  • 88

4 Answers4

2

You might use endsWith and use @gmail.com like:

"test@gmail.com".endsWith("@gmail.com")

Or use a regex like ^\S+@gmail\.com$

Details

  • ^ Assert position at the start of the line
  • \S+ Match any non whitespace characters one or more times
  • @gmail\.com match @gmail.com
  • $ Assert position at the end of the line

For example

if ("test@gmail.com".matches("^\\S+@gmail\\.com$")) {
    System.out.println("Match!");
}

Demo Java

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

You could make use of regex.

Pattern p = Pattern.compile(".*@gmail\.com");
Matcher m = p.matcher("hello@gmail.com");
boolean b = m.matches();
Ron Nabuurs
  • 1,528
  • 11
  • 29
0

The simplest solution would be checking if the email contains the specified domain. Later you could add a regex or even a dictionary to store the different domains, instead of using one method for each individual domain.

private boolean isFromGmailDomain(String email, String domain)
{
    return email.contains(domain);
}
miguelarc
  • 791
  • 7
  • 13
0

You could make use of regex. You can check regex https://www.regextester.com/94044

^[a-zA-Z0-9_.+-]+@(?:(?:[a-zA-Z0-9-]+.)?[a-zA-Z]+.)?(domain.in|domain2.com)

Ashish Chaugule
  • 1,526
  • 11
  • 9