Guides
Last updated
July 25, 2025

5 Ways to Validate Emails with Apache Commons Validator

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
email validation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Validating email addresses in Apache is a common requirement for data quality. We'll walk through five implementation methods using commons-validator, showing code examples for each. Then, we'll examine the pitfalls of these approaches and see how Abstract API offers a more complete solution to overcome them.

How to Implement Apache Email Validator

The commons-validator library offers several ways to check email addresses. Below are four methods, each with a different level of configuration, from a simple singleton to a custom validator.

Stateless Default Singleton

This method uses a stateless, default singleton instance of the EmailValidator. The `getInstance()` method returns this shared instance, which conceals the constructor details from the user. The `isValid(String)` method then performs a quick validation based on character validity, length, and a minimal domain structure check.

EmailValidator v = EmailValidator.getInstance();
boolean ok = v.isValid("alice@example.com");

Flag-Configured Singleton (Local Parts, Bare TLDs)

This approach also uses a singleton but configures it with boolean flags. The first flag, `allowLocal`, permits host-less addresses like 'svc@localhost', which are common in test environments or for internal service calls. The second flag, `allowTld`, accepts addresses like 'admin@apache', useful when you operate behind a corporate SMTP relay.

The validator uses the same singleton mechanism, so there is no performance cost from object allocation. The code below shows how to enable both flags when you get the instance.

EmailValidator v = EmailValidator.getInstance(true, true);   // allowLocal, allowTld
boolean ok = v.isValid("svc@localhost");

Custom DomainValidator Injection

This method provides more control through the injection of a custom `DomainValidator`. The three-argument constructor for `EmailValidator` lets you completely override the default domain-check strategy. This is useful to whitelist private zones or ship an offline Top-Level Domain (TLD) snapshot.

The code shows how to use the DomainValidator.builder() to configure custom rules. You can add private TLDs like 'corp' or 'internal' and accept host-only names. This custom validator is then passed to the `EmailValidator` constructor.

DomainValidator dv = DomainValidator.builder()
        .addCustomTld("corp")               // private TLD
        .addCustomTld("internal")           // non-IANA zone
        .allowLocal(true)                   // accept host-only names
        .build();
EmailValidator v = new EmailValidator(true, false, dv);
boolean ok = v.isValid("bob@payments.corp");

Pure Regular-Expression Validator via RegexValidator

For a pure regular-expression approach, you can use the `RegexValidator` class. This validator is part of the same commons-validator module and offers simple `isValid`, `validate`, and `match` helper functions for your pattern.

This allows you to embed the core logic from RFC-5322 without the `EmailValidator` domain logic or IANA data. This is an attractive option for very small services or in environments where the full Apache commons package is already reduced for size.

RegexValidator rx = new RegexValidator(
        "^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+" +
        "@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,}$");
boolean ok = rx.isValid("carol@sub.example.net");

Challenges of Apache Email Validator

The library's age and design choices introduce several pitfalls. These issues range from outdated regular expressions to unpredictable behavior, which can complicate validation logic and create technical debt for development teams.

  • The core regex in `EmailValidator` and `RegexValidator` fails to implement the full RFC grammar. This loose, blacklist-driven approach incorrectly validates broken addresses while it rejects some legal edge cases, which creates inconsistent results.
  • The default validator accidentally permits non-ASCII characters because its pattern lacks positive rules. This makes it impossible to enforce a clear "ASCII-only" policy without custom code to wrap the `isValid` method.
  • The `allowLocal` and `allowTld` flags in the `getInstance` method alter behavior globally. A single parameter change can unexpectedly permit dotless domains, which breaks shared validation logic across different modules.
  • Unresolved Jira tickets recommend a complete rewrite of the class. Teams that use the library inherit this technical debt and must patch or wrap the validator themselves to achieve predictable RFC compliance.

Validate Emails with Abstract API
Use the Commons Email Validator library to ensure only valid email addresses enter your system.
Get started for free

How Abstract API Addresses the Shortcomings of Apache's Email Validator

To address the core weaknesses of regex-based validation, Abstract API performs real-time deliverability checks and provides detailed quality signals.

  • It performs real-time DNS and SMTP probes, which removes the need for local network code and complex firewall exceptions.
  • It returns a detailed JSON response with a deliverability status and a numeric quality score, which offers more nuance than a simple valid or invalid flag.
  • The API provides flags to identify disposable, role-based, catch-all, and free email providers to help prevent abuse.
  • It suggests corrections for common typos, which allows you to fix user input instead of just reject it.

How to Set Up Abstract API in Your Project

Once you know Abstract’s capabilities, the addition of its email validator API to your project is simple.

  • First, sign up at Abstract API, enable the Email Verification & Validation feature, and copy your API key.
  • Add an HTTP client library to your project.
  • Store the key in an environment variable, for example, ABSTRACT_EMAIL_KEY.
  • Build the request URL with your API key and the email you want to check.
  • Call the endpoint from your service layer and parse the JSON response.
  • Gate user flows based on the deliverability status and quality score.

This Java snippet shows a basic implementation of an API call.

String apiKey = System.getenv("ABSTRACT_EMAIL_KEY");
String email  = URLEncoder.encode(userEmail, StandardCharsets.UTF_8);
HttpGet req   = new HttpGet("https://emailvalidation.abstractapi.com/v1/?api_key="
               + apiKey + "&email=" + email);
try (CloseableHttpClient c = HttpClients.createDefault();
     CloseableHttpResponse r = c.execute(req)) {
    String json = EntityUtils.toString(r.getEntity());
    JSONObject o = new JSONObject(json);
    if ("DELIVERABLE".equals(o.getString("deliverability"))) { … }
}

Sample Implementation with Abstract API

The API returns a detailed JSON object. This response offers much more than a simple valid or invalid status. For example, a call for the email dev@apache.org returns the following data.

{
 "email":"dev@apache.org",
 "autocorrect":"",
 "deliverability":"DELIVERABLE",
 "quality_score":0.97,
 "is_valid_format":{"value":true,"text":"TRUE"},
 "is_free_email":{"value":false,"text":"FALSE"},
 "is_disposable_email":{"value":false,"text":"FALSE"},
 "is_role_email":{"value":false,"text":"FALSE"},
 "is_catchall_email":{"value":false,"text":"FALSE"},
 "is_mx_found":{"value":true,"text":"TRUE"},
 "is_smtp_valid":{"value":true,"text":"TRUE"}
}

The address passes all syntax, MX, and SMTP checks. It is not a disposable, free, role-based, or catch-all address. The 0.97 quality score and DELIVERABLE flag show high confidence that messages will reach an inbox, a guarantee Apache Commons EmailValidator alone cannot provide.

Final Thoughts

Traditional methods often rely on regex, which fails to confirm if an email address can actually receive mail. This approach accepts syntactically valid but undeliverable addresses. Abstract API solves this with real-time checks for deliverability and provides detailed quality scores. To reliably validate user emails, consider an account on Abstract API to get your free API key.

Validate Emails with Abstract API
Implement the Apache email validator to ensure only valid email addresses can enter your system.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required