How to use MailboxValidator Symfony Bundle to validate email?

Overview

The MailboxValidator Symfony Email Validation Bundle is an easy to use Symfony package which enables Symfony users to validate emails with just a few lines of code. This package is using the MailboxValidator API to do the validation, therefore you must sign up for the API key. Just go to https://www.mailboxvalidator.com/plans#api to sign up for the FREE API plan and you’ll be given an API key.

Dependencies

This bundle requires Symfony 4.3 to work. The MailboxValidator PHP Module is also required and will be auto installed by Composer. In case your Composer did not install it for you, you can get it from here: https://github.com/MailboxValidator/mailboxvalidator-php .

Installation

Once you have the API key, the next step is to install the package by using Composer. Open your terminal, navigate to your project root directory and type the following command:

composer require mailboxvalidator/mailboxvalidator-bundle

Composer will then install the bundle into your web application. After that, load a .env file in your PHP application via Dotenv::load().

use Symfony\Component\Dotenv\Dotenv;

$dotenv = new Dotenv();

$dotenv->load(__DIR__.'/.env'); //Your .env file path

Then, open your .env file and add the following line:

MBV_API_KEY=PASTE_YOUR_API_KEY_HERE

Usage

To use any one of the three validators or to use all of the validators, include the following lines in any form controllers that handle validations:

use MailboxValidatorBundle\Validator\MBVSingle;

use MailboxValidatorBundle\Validator\MBVDisposable;

use MailboxValidatorBundle\Validator\MBVFree;

After that, add a new rule to your form field and edit the error message. For example, if you want to validate the disposable email, your rule will be like this:

->add('email', EmailType::class, [

    'constraints' => [

        new MBVDisposable([

            //You can also customize your own message. For example,

            //'message' => 'This email is disposable. Please enter another email again.',

        ]),

    ],

])

The bundle provides three different validation methods: disposable, single and free. Single Validation will validate the email address based on several factors, such as whether the email address contains high risk keywords or whether the email address is in our blacklist. Disposable Validation will validate whether the email address belongs to a disposable email service provider or not. Free Validation will validate whether the email address belongs to a free email service provider or not.

Now, you can try to open your form and enter a disposable email address. The validator should return an error message once the submit button is clicked.

 

 


Get started with MailboxValidator

Improve your email deliverability and sender reputation in email marketing.

Register today and clean your email lists for FREE!


 

Was this article helpful?

Related Articles