Published on: by Jason Gilmore
Email validation is a common task for developers. It is a crucial step in ensuring that the email address provided by a user is valid and exists. This is important because it helps prevent bounced emails and failed deliveries, which can negatively impact your business. In this post you'll learn how to validate an email address in PHP using regular expressions, PHP's filter_var()
function, and Laravel's email validator. You'll also learn why syntactical email validation often isn't enough to ensure a human will be reading emails you send to that address, and how you can use EmailReputationAPI to avoid sending emails to disposable email addresses, spam traps, and other irrelevant destinations.
The typical email address is easily recognizable, often using a format such as [email protected]
. But did you know that email addresses such as this.”is\”[email protected]
, [email protected]
, and [email protected]
are also valid? Meanwhile, addresses such as X and Y are not valid. These arcane rules are defined in RFC 5322, which defines the syntax of email addresses.
Because there are so many syntax variations, creating an email verifier from scratch will require the use of a regular expression. Regular expressions are a sequence of characters that define a search pattern. They are used to match, search, and replace text. In this case, we want to match a string that matches the syntax of an email address. Needless to say, a lot of ink has been spilled debating the ideal email validation regular expression. Check out a few of my favorite online resources about the topic:
Of course, most developers would rightfully desire to just incorporate working validation code into their application rather than spend time pondering esoteric RFC details, so here's a regular expression that will validate an email address in PHP:
function isValidEmailUsingRegex($email) { $pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/'; return preg_match($pattern, $email); } $email = '[email protected]'; echo isValidEmailUsingRegex($email) ? 'valid' : 'invalid';
There are caveats to using regular expressions (as well as the two following strategies) to validate email addresses, because they only check the syntax of the email address. They do not check whether the email address actually exists, is deliverable or is reputable. For example, the email address [email protected]
would be identified as valid when using the above code, despite the fact nospam
not being a valid TLD (top-level domain). In fact, I'd be willing to bet the list of supported TLDs is far larger than you would expect. See this list for a complete list of TLDs.
filter_var()
function is a built-in function that filters a variable with a specified filter. It returns the filtered data on success, or false
on failure. The following example uses the FILTER_VALIDATE_EMAIL
filter to validate an email address:
$email = '[email protected]'; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo 'Valid email address'; } else { echo 'Invalid email address'; }
If more succinct syntax is preferred, you could substitute the if conditional for a ternary statement:
$email = '[email protected]'; $valid = filter_var($email, FILTER_VALIDATE_EMAIL) ? true : false;
Learn more about the filter_var()
function in the PHP documentation.
Users of the popular Laravel framework can use the email
validation rule to validate email addresses. The email
rule will check if the email address is valid and has a valid MX record. The email
rule uses PHP's filter_var()
function under the hood, so it will not check if the email address is deliverable or reputable. Here's an example of using the email
rule to validate an email address:
use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; public function validateEmail(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email', ]); if ($validator->fails()) { return redirect('your-form-url') ->withErrors($validator) ->withInput(); } // If the validation passes, continue with your logic here }
As mentioned above, syntactical email validation is not enough to ensure a human will be reading emails you send to that address. EmailReputationAPI is a service that provides a simple API to validate email addresses. It uses a combination of machine learning and an extensive database to determine whether an email address is valid, deliverable, and reputable. It also checks if the email address is a disposable (anonymized) email address, or uses a personal email service such as Hotmail or Gmail. You can use the API to validate email addresses in real-time, or in bulk. Here's an example of the response our API will return with validating an email address:
{ "email": "[email protected]", "syntax": "valid", "tld": "true", "personal": "false", "disposable": "true", "government": "false", "business": "false", "unknown": "false" }
Check out the documentation at https://www.emailreputationapi.com/docs to learn more.