In this tutorial, we will demonstrate how to use the MailboxValidator Yii extension to validate email addresses. MailboxValidator Yii extension provides an easy way to use the MailboxValidator API to validate email addresses. As this library is using the MailboxValidator API, you must obtain a free API key to use this library. Just go to https://www.mailboxvalidator.com/plans#api to sign up for the FREE API plan and you’ll be given a free API key. After you get your API key, open your config/params.php and add this line in the array:
'mbvAPIKey' => 'PASTE_YOUR_API_KEY_HERE',
Install this extension by using composer with this command in the console:
composer require mailboxvalidator/mailboxvalidator-yii
This extension can be used to validate an email address. For example, validate an email address called “firstname.lastname@example.org” and get the validation result for that email address. To do so, first load the library in your controller:
After that, you can load your API key and retrieve the validation result for the email address like this:
<code class="enlighterjsraw" data-enlighter-language="php">$mbv = new SingleValidation(Yii::$app->params['mbvAPIKey']);<br > $results = $mbv->FreeEmail('email@example.com');</br ></code class="enlighterjsraw" data-enlighter-language="php">
Note that the ‘mbvAPIKey’ is the variable of the MailboxValidator API key and the variable name should not be changed. Next, to pass the result to the view, just add the $results to your view render like this:
return $this->render('YOUR_VIEW_NAME', ['results' => $results]);
And after that in your view file, call the validation results. For example:
echo 'email_address = ' . $results->email_address . "<br>";
You can refer the full list of response parameters available at here: https://www.mailboxvalidator.com/api-single-validation.
The library can also help with form validation. How to do so? Firstly, call this library in your model like this:
After that, in the function rules, add the new validator rule for the email:
['YOUR_EMAIL_FIELD_NAME', MailboxValidator::className(), 'option'=>'disposable,free',],
In this line, the extension is called, and you will need to specify which validator to use. The available validators are disposable and free. Finally, open or refresh your form and try to submit an invalid email address to see the outcome. You shall see the error message if the email address is invalid.