2

I am trying to validate email in my custom controller file. Here is the code that i am trying...

if (!\Zend_Validate::is(trim('test@r-u-i-.com'), 'EmailAddress')) {
    echo "not valid";
}else{
    echo "valid...";
}

This validation return me that this is a valid email address. But when i am trying to create customer, Magento return me this error "Email has a wrong format"

0

3 Answers 3

4

Ok finally i found the solution.

Actually M2 return "Email has a wrong format" this error from following file

magento\module-sales\Model\Order\Address

And in this method there is a email validation

public function validate(Address $address)
    {
        $warnings = [];
        foreach ($this->required as $code => $label) {
            if (!$address->hasData($code)) {
                $warnings[] = sprintf('%s is a required field', $label);
            }
        }
        if (!filter_var($address->getEmail(), FILTER_VALIDATE_EMAIL)) {
            $warnings[] = 'Email has a wrong format';
        }
        if (!filter_var(in_array($address->getAddressType(), [Address::TYPE_BILLING, Address::TYPE_SHIPPING]))) {
            $warnings[] = 'Address type doesn\'t match required options';
        }
        return $warnings;
    }

So i simply used the code from this method.

if (!filter_var("test@r-u-i-.com", FILTER_VALIDATE_EMAIL)) {
     $warnings[] = 'Email has a wrong format';
}
3

You should use Email Validator class:

\Magento\Framework\Validator\EmailAddress

Usage example: \Magento\CustomerGraphQl\Model\Resolver\IsEmailAvailable

/** @var \Magento\Framework\Validator\EmailAddress $this->emailValidator */
if (!$this->emailValidator->isValid($args['email'])) {
    throw new GraphQlInputException(__('Email is invalid'));
}
1
  • A great solution - thank you!
    – PromInc
    Jan 13 at 15:07
1

To validate email in controller file you can use below code, hope this will help you.

$postObject = new \Magento\Framework\DataObject();
$postObject->setData($post);

$error = false;

if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
    $error = true;
}
if (!\Zend_Validate::is(trim($post['comment']), 'NotEmpty')) {
    $error = true;
} 
if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
    $error = true;
}
if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
    $error = true;
}
if ($error) {
    throw new \Exception();
}
1
  • 1
    This is the same as my question.
    – Hardik
    May 15, 2018 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.