Validating emails in Magento 2 is very crucial because it helps to make sure you don’t get any fake email submissions and that the information provided by users is proper.
You can validate email addresses programmatically inside the PHP-based files of your Magento 2 codebase.
You can use native
Magento\Framework\Validator\EmailAddress emailValidator class to validate email address.
Let’s understand it with a quick and easy example.
<?php
/**
*
* Tutorial by Jigar Karangiya Blogs, hello@jigarkarangiya.com
* Visit jigarkarangiya.com for more magento 2 blogs.
*/
use Magento\Framework\Validator\EmailAddress as EmailValidator;
use Magento\Framework\App\ObjectManager;
/**
* Validate email address format
*
*/
class YourClass
{
/**
* @var EmailValidator
*/
private $emailValidator;
/**
* Initialize dependencies.
*
* @param EmailValidator $emailValidator
*/
public function __construct(
EmailValidator $emailValidator = null
) {
$this->emailValidator = $emailValidator ?: ObjectManager::getInstance()->get(EmailValidator::class);
}
/**
* Validates the format of the email address
*
* @param string $email
* @throws Exception
* @return boolean
*/
public function isValidEmail($email)
{
try {
if (!$this->emailValidator->isValid($email)) {
return false;
} else {
return true;
}
} catch (Exception $e) {
//Handle exception here
}
}
}
You can then use it using by calling function $this->isValidEmail(‘hello@jigarkarangiya.com’);
It will return true or false based on the email address provided.
I hope this article helped you to find what you were looking for.
Bookmark it for your future reference. Do comment below if you have any other questions on that.
Do share this blog with your team.
You will also like this :
how to get shared catalog data by ID in Magento 2?
Get Company using Customer ID programmatically Magento 2 B2B
Get Company Admin using company ID programmatically Magento 2 B2B
Leave a Comment