0
0
JavaHow-ToBeginner · 3 min read

How to Validate Email Using Java: Simple and Effective Method

To validate an email in Java, use the Pattern and Matcher classes with a regular expression that matches the email format. Alternatively, use javax.mail.internet.InternetAddress for more robust validation by checking the email syntax.
📐

Syntax

Use the Pattern class to compile a regular expression that defines the email format. Then use Matcher to check if the input string matches this pattern.

Example regex parts explained:

  • ^[A-Za-z0-9+_.-]+: Start with allowed characters before '@'
  • @: The '@' symbol separating local and domain parts
  • [A-Za-z0-9.-]+$: Domain name with allowed characters
java
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class EmailValidator {
    private static final String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";

    public static boolean isValidEmail(String email) {
        Pattern pattern = Pattern.compile(EMAIL_REGEX);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}
💻

Example

This example shows how to use the isValidEmail method to check different email strings and print whether they are valid or not.

java
public class Main {
    public static void main(String[] args) {
        String[] emails = {
            "user@example.com",
            "user.name+tag+sorting@example.com",
            "user@.invalid.com",
            "user@domain",
            "@nouser.com"
        };

        for (String email : emails) {
            boolean valid = EmailValidator.isValidEmail(email);
            System.out.println(email + " is valid? " + valid);
        }
    }
}

// EmailValidator class from previous section should be included in the same package or file.
Output
user@example.com is valid? true user.name+tag+sorting@example.com is valid? true user@.invalid.com is valid? false user@domain is valid? true @nouser.com is valid? false
⚠️

Common Pitfalls

Common mistakes when validating emails in Java include:

  • Using too simple regex that accepts invalid emails like missing domain parts.
  • Not handling null or empty strings before validation.
  • Assuming regex can catch all invalid emails; some invalid emails pass regex but are not deliverable.
  • Not trimming input strings to remove spaces.

For more accurate validation, use javax.mail.internet.InternetAddress which parses and validates email syntax.

java
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

public class EmailValidatorAdvanced {
    public static boolean isValidEmail(String email) {
        if (email == null || email.trim().isEmpty()) {
            return false;
        }
        try {
            InternetAddress emailAddr = new InternetAddress(email);
            emailAddr.validate();
            return true;
        } catch (AddressException ex) {
            return false;
        }
    }
}
📊

Quick Reference

Summary tips for email validation in Java:

  • Use regex with Pattern and Matcher for simple format checks.
  • Use InternetAddress for more reliable syntax validation.
  • Always check for null or empty strings before validating.
  • Trim input to remove leading/trailing spaces.
  • Remember regex cannot guarantee deliverability, only format correctness.

Key Takeaways

Use Java's Pattern and Matcher classes with a regex to check email format.
For stronger validation, use javax.mail.internet.InternetAddress to parse and validate emails.
Always handle null or empty inputs before validation to avoid errors.
Regex validation checks format but does not guarantee the email is deliverable.
Trim input strings to avoid false negatives due to spaces.