Guides
Last updated
November 16, 2023

How to Validate Emails with CakePHP

Shyam Purkayastha

Table of Contents:

Get your free
Email Validation
API key now
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

Email address validation is one of the most commonly implemented logic in web development. As a popular PHP framework, CakePHP offers built-in support for email validation. However, there is more to email validation than just checking the address format and the ‘@’ symbol.

In this article, we will show you a tutorial on how to validate the email field in CakePHP using various options. We will also address the issue of checking the email address and domain legitimacy and integrate such advanced validations within a CakePHP project. But before we get into the details of email validation, let’s set up CakePHP.

Related:
- How to validate emails with PHP
- Validate emails with PHP and regex

Let’s send your first free
Email Validation
call
See why the best developers build on Abstract
Get your free api

Setting up CakePHP

CakePHP is a PHP web framework that follows the popular MVC (Model View Controller) architecture. Initially written in 2005, it has enjoyed a good following since then and has amassed over 8k stars on GitHub. CakePHP is under active development and is used by many small and large enterprises.

Installing CakePHP

CakePHP can be installed as a dependency for a PHP project by running the composer, the de-facto PHP dependency manager. Let’s create a new PHP project with CakePHP. Before starting, make sure to have one of the latest versions of :

  • PHP (version 8.1 or later).
  • Composer (version 2.3 or later).

Open a command line terminal and change to a suitable directory. After that, run the following composer command to create a new PHP project config with the CakePHP framework.


composer create-project --prefer-dist cakephp/app CakeEmailValidator

This command will create a new project named ‘CakeEmailValidator’ and install the latest CakePHP version, among other dependencies. A top-level directory with the same name is created in the current path. The sub-directory structure of this directory is as follows.

Testing CakePHP

This project contains a skeletal CakePHP web app you can test using the built-in development server. Run the following command to start the server.


bin/cake server

This command will start the web app on port 8765 with a valid URL. Point your browser to the URL http://localhost:8765/, and you should see the default web page of the app.

Understanding Validations in CakePHP

CakePHP provides validation classes with a rich set of off-the-shelf validation rules for validating input data submitted through web forms. In the case of a form containing an email field, you have multiple approaches to validate it within CakePHP.

  1. Default validation: Using the Validation::email( ) method to validate the email format, with an option to perform deep validation for checking the email domain and MX records.
  2. Custom Validation: Using the class Validator to define custom rules related to email id format, domain, or additional  regex based rules.
  3. API Validation: Using the class Client to make an API call to an external email validation service.

Let’s build a demo email validation application using all three options.

How to Validate Email Field in CakePHP

There are always two parts to a web application: the front end and the back end. Let's first build the frontend web page for validating the email field. In a CakePHP project, the frontend views are stored in the 'templates' subdirectory within the project directory.

Inside the 'templates' subdirectory, create a new directory named 'emailValidator' and create a new file named 'index.php' within that directory. Open this file in a code editor and replace the content with the below code.

File:  ‘templates/emailValidator/index.php’




Form->create() ?>
Form->input('email', array('style' => 'margin-right:10px')) ?>
Form->button(__('Submit')) ?>
Form->end() ?>







    $fieldErrors): ?>










Valid email address


This code adds a simple HTML form with an email field and a submit button. A separate <div> section is added to conditionally display the list of errors based on the response from the backend after form submission.

This front end will be used for all the validation demonstrations you will see later in this article.

Now, to handle the form submission at the backend, run the following command from another terminal after changing the directory to the top-level ‘CakeEmailValidator’ directory.


bin/cake bake controller EmailValidator

This command creates a new controller within the CakePHP project under ‘src/Controller’ path. This is a PHP source file.


Open the new PHP controller file in a code editor and replace the default code with the following code:

File: ‘src/Controller/EmailValidatorController.php’



namespace App\Controller;

use Cake\Validation\Validation;


class EmailValidatorController extends AppController
{
public function index()
{
$email = '';
$errors = [];
$success = false;
if ($this->request->is('post')) {
$email = $this->request->getData('email');

if (!Validation::email($email)) {
$errors['email'][] = 'Invalid email address';
}
if (empty($errors)) {
$success = true;
}
}

$this->set(compact('email', 'errors', 'success'));
}
}

This code adds a new method of action named index, which gets executed upon form submission from the front end. This code first checks if the request method is a POST request. It ensures the code inside the if block is executed when the user submits the form. After that, it retrieves the user-provided email from the form data submitted via POST.

For validating the email field, this code uses the first approach of default validation presented earlier. It imports the built-in CakePHP Validation class and calls the email( ) method, which returns a boolean value.

Upon saving this file, your CakePHP application has a new URL path,  ‘http://localhost:8765/emailValidator/index’ for performing default validation on email.

Open this URL in the browser and test it by submitting an email address. You should see success and failure responses for valid and invalid email address formats, respectively.

Advanced Email Validation Techniques

The default validation is good when you want to guard against junk input data that does not resemble an email address. But if you enforce specific rules for creating or accepting email addresses, you need CakePHP's custom validation features.

To create a custom validation rule, define a new validation method in the EmailValidator Controller and name it customValidation(). Add this method within the EmailValidatorController class with the following logic.

File: ‘src/Controller/EmailValidatorController.php’


public function customValidation()
{
$this->viewBuilder()->setTemplate('index');
$email = '';
$errors = [];
$success = false;

if ($this->request->is('post')) {
$email = $this->request->getData('email');
$validator = new Validator();
$validator
->email('email', true, 'Invalid email format.')
->add('email', 'allowedDomains', [
'rule' => function ($value) {
$allowedDomains = ['gmail.com', 'outlook.com'];
$domain = explode('@', $value);
return in_array(end($domain), $allowedDomains);
},
'message' => 'Email domain is not allowed',
])
->add('email', 'noMultipleDash', [
'rule' => function ($value) {
return substr_count($value, '-') === 0;
},
'message' => 'Email should not contain "-" symbols',
]);

$errors = $validator->validate(['email' => $email]);
if (empty($errors)) {
$success = true;
}
}

$this->set(compact('email', 'errors', 'success'));
}

Note: As a good coding practice, all validation logic should be defined in separate models and controllers. However, for the sake of simplicity, the code presented here is contained in a single controller.

The customValidation() method creates a Validator object that defines two custom rules in addition to the default validation.

  1. allowedDomains: This rule enforces that the email address should contain only a list of allowed domains. In this code, the rule only allows “gmail.com” and “outlook.com” domains. In this way, you can restrict the submission of email addresses with specific domain names only.
  2. noMultipleDash: This rule enforces that the email address should not contain any dash , ‘-’ symbols. This rule is helpful in case you want to restrict email addresses having special characters.

When this code is triggered, the Validator object runs through these custom rules in sequence to check the email syntax and accumulates the errors in the $errors variable based on the bool return value of each rule. This data is passed on to the front end for displaying on the web page.

You can also add more custom rules using the add( ) method of class Validator for alphanumeric, numeric, regular expressions, and other validation checks.

Before saving this file, add this line of code to import the class Validator, just below the namespace declaration at the top.


use Cake\Validation\Validator;

This new validation method is now accessible from the URL http://localhost:8765/emailValidator/customValidation. Open this URL on the browser, and now you can test these rules.


A Better Solution: AbstractAPI

Having custom rules for email address validation is a good idea, but sometimes, it's a better approach to rely on a reliable API service. The Abstract Email Validation & Verification API is one such reliable and robust service that offers a host of options to verify and flag emails based on several criteria.

You can sign up for the Abstract account and get access to 100 free requests by using the API key that is assigned to your account upon logging in to the API dashboard page.

Let’s integrate the Abstract Email Validation and Verification API. To achieve that, define one more method named abstractAPIValidation( ).

File: ‘src/Controller/EmailValidatorController.php’


public function abstractApiValidation()
{
$this->viewBuilder()->setTemplate('index');
$email = '';
$errors = [];
$success = false;

if ($this->request->is('post')) {
$email = $this->request->getData('email');

$httpClient = new Client();
$response = $httpClient->get("https://emailvalidation.abstractapi.com/v1/?api_key=&email=$email");
$data = $response->getJson();

if (!isset($data['is_valid_format']['value']) || !$data['is_valid_format']['value']) {
$errors['email'][] = 'Invalid email format';
}

if (isset($data['is_smtp_valid']['value']) && !$data['is_smtp_valid']['value']) {
$errors['email'][] = 'Not a valid SMTP';
}

if (empty($errors)) {
$success = true;
}
}

$this->set(compact('email', 'errors', 'success'));
}

This method uses the CakePHP’s Client class from Http namespace. Make sure to include it at the top after the namespace declaration.


use Cake\Http\Client;

This method makes an HTTP GET request to the Abstract API endpoint and retrieves the response to parse the validation status. In this code, the validation is limited to checking the email address format and SMTP to ascertain the email address domain’s mail server capabilities. But you can also add additional validations as per the documentation of this API.

Before saving the file, replace the placeholder <ABSTRACT_API_KEY> with your Abstract account’s API key. Now you have one more URL endpoint to test this validation: http://localhost:8765/emailValidator/abstractApiValidation.

Here is how you can test it for invalid and valid email addresses.

Here is the complete EmailValidatorController.php file with the three email validation options you have just learned.



namespace App\Controller;

use Cake\Validation\Validation;

use Cake\Validation\Validator;

use Cake\Http\Client;


class EmailValidatorController extends AppController
{
public function index()
{
$email = '';
$errors = [];
$success = false;
if ($this->request->is('post')) {
$email = $this->request->getData('email');

if (!Validation::email($email)) {
$errors['email'][] = 'Invalid email address';
}
if (empty($errors)) {
$success = true;
}
}

$this->set(compact('email', 'errors', 'success'));
}

public function customValidation()
{
$this->viewBuilder()->setTemplate('index');
$email = '';
$errors = [];
$success = false;

if ($this->request->is('post')) {
$email = $this->request->getData('email');
$validator = new Validator();
$validator
->email('email', true, 'Invalid email format.')
->add('email', 'allowedDomains', [
'rule' => function ($value) {
$allowedDomains = ['gmail.com', 'outlook.com'];
$domain = explode('@', $value);
return in_array(end($domain), $allowedDomains);
},
'message' => 'Email domain is not allowed',
])
->add('email', 'noMultipleDash', [
'rule' => function ($value) {
return substr_count($value, '-') === 0;
},
'message' => 'Email should not contain "-" symbols',
]);

$errors = $validator->validate(['email' => $email]);
if (empty($errors)) {
$success = true;
}
}

$this->set(compact('email', 'errors', 'success'));
}

public function abstractApiValidation()
{
$this->viewBuilder()->setTemplate('index');
$email = '';
$errors = [];
$success = false;

if ($this->request->is('post')) {
$email = $this->request->getData('email');

$httpClient = new Client();
$response = $httpClient->get("https://emailvalidation.abstractapi.com/v1/?api_key=&email=$email");
$data = $response->getJson();

if (!isset($data['is_valid_format']['value']) || !$data['is_valid_format']['value']) {
$errors['email'][] = 'Invalid email format';
}

if (isset($data['is_smtp_valid']['value']) && !$data['is_smtp_valid']['value']) {
$errors['email'][] = 'Not a valid SMTP';
}

if (empty($errors)) {
$success = true;
}
}

$this->set(compact('email', 'errors', 'success'));
}
}

Conclusion

We have shown you how to validate email addresses within a CakePHP application. You can choose one of the three options depending on your use case. While the default and custom validation are suited for general validations, they do not guarantee the deliverability and quality of email addresses. With Abstract Email Validation and Verification API, you have these options, which would otherwise require you to send a test email.

FAQ

How to validate email using CakePHP?

CakePHP offers a few validation options specifically for email addresses. For basic validation, you can use the email( ) method from the Validation class. It can perform basic email address format checks. For custom validation involving filtering of email addresses based on domain names and special characters, you can use the Validator class. Using the add( ) method of this class, you can include custom validation rules related to email address length, characters, and domains. It gives you complete control over the input data submitted through web forms, be it email addresses or any other form of data. For more legitimate validation, you can use the Abstract Email Validation and Verification API, which lets you ascertain the email address's deliverability without sending a test mail.

How do you verify and validate email addresses in PHP?

PHP offers some built-in functions for data validation. In the case of email, you can use the filter_var( ) function. It accepts several pre-configured filter types, including FILTER_VALIDATE_EMAIL, for validating email addresses. If you are building a PHP application using some popular frameworks, you have more options. For example, in the case of CakePHP, you can use CakePHP's Validator class to define custom rules. Alternatively, you can also use an email validation API. The Abstract Email Validation and Verification API offers a robust, reliable, and authentic service for validating email addresses. It provides much information about any email's deliverability, domain, quality, and other traits.

What are the email validation rules in CakePHP?

Under CakePHP's Validation namespace, there are a few classes that are designed to offer different ways of validating email addresses. The Validation class contains methods for validating pre-formatted data like email address, URL, date, hex color code, etc. For email, you can call the email( ) method to perform basic format validation of an email address. For more granular validation, down to the email id and domain level, you can leverage the Validator class with custom rules. You can also build more complex validation logic using the ValidationRule and ValidationSet classes.

Shyam Purkayastha

Shyam Purkayastha is a proficient web developer and PHP maestro, renowned for his expertise in API creation and integration. His deep knowledge of PHP scripting and backend development enables him to build scalable server-side applications. Shyam is particularly passionate about RESTful API design, significantly enhancing web service functionality and data interoperability.

Get your free
Email Validation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
Email Validation
key now
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