Email Validation Pattern

Validate user emails with a conservative regex pattern that accepts common shapes and rejects spaces or missing domains.

JavaForm Validation

Code

javasnippet
22 lines
import java.util.regex.Pattern;

public class EmailValidator {

    // conservative email validation: local@domain.tld, no comments, no quoted local part
    static final Pattern EMAIL = Pattern.compile(
            "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");

    static boolean valid(String value) {
        return value != null && EMAIL.matcher(value).matches();
    }

    public static void main(String[] args) {
        String[] candidates = {
                "ada@example.com", "ada.lovelace@mail.example.co.uk",
                "ada+tag@example.com", "missing-at-sign.example.com",
                "no-domain@", "spaces in@example.com"};
        for (String candidate : candidates) {
            System.out.println(candidate + " -> " + valid(candidate));
        }
    }
}

Inside the snippet

All of the logic lives in the class EmailValidator and the functions valid and main.

The cycling part of this snippet is for (String candidate : candidates).

What to watch for

  • No dependency machinery at all — no registry file and no lockfile entry.

Using it

The signature you will call most reads static boolean valid(String value)

Start the program and main runs valid one after another.

The key statements, annotated

return value != null && EMAIL.matcher(value).matches();

Interactive Tools for This Topic

FAQ

How do you run Email Validation Pattern?
Just run the file; everything it needs ships with the runtime itself.