Magento 2 : Skip Customer Name Validation

Have you ever faced error that says The Customer First name is Invalid if Yes ? then this is the solution.

First Name is not valid magento 2

There comes a time when you want to add special character to customer first name , last name or middle name . Or in My case after migration there were some customers with special characters in their names. So in my case I need to Skip customer name validation.
So When ever I try to save the customer it gives the error of “First Name is not valid!” Example. So we will look into the solution of allowing special character while saving customers or skip it for a while. the customer name validation by overriding the functionality that is causing this by default.
When we trace the error of First Name is Not Valid we can see that This issue is from the class

\Magento\Customer\Model\Validator\Name::isValidName

So to Counter this issue we can skip this validation for now by overriding this class for that you have to override this class by preference

in di.xml

<preference for="Magento\Customer\Model\Validator\Name" type="Gm\Module\Model\Validator\Name"/>
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace GM\Module\Model\Validator;

use Magento\Customer\Model\Customer;
use Magento\Store\Model\ScopeInterface;

/**
 * Customer name fields validator.
 */
class Name extends \Magento\Customer\Model\Validator\Name
{
    private const PATTERN_NAME = '/(?:[\p{L}\p{M}\,\-\_\.\'’`\s\d]){1,255}+/u';

    /**
     * Validate name fields.
     *
     * @param Customer $customer
     * @return bool
     */
    public function isValid($customer)
    {
        $skip_validation = false;//write the condition if you want to add one here
        if ($skip_validation) {
            if (!$this->isValidName($customer->getFirstname())) {
                parent::_addMessages([['firstname' => 'First Name is not valid!']]);
            }
            if (!$this->isValidName($customer->getLastname())) {
                parent::_addMessages([['lastname' => 'Last Name is not valid!']]);
            }
            if (!$this->isValidName($customer->getMiddlename())) {
                parent::_addMessages([['middlename' => 'Middle Name is not valid!']]);
            }
        }
        return count($this->_messages) == 0;
    }

    /**
     * Check if name field is valid.
     *
     * @param string|null $nameValue
     * @return bool
     */
    private function isValidName($nameValue)
    {
        if ($nameValue != null) {
            if (preg_match(self::PATTERN_NAME, $nameValue, $matches)) {
                return $matches[0] == $nameValue;
            }
        }
        return true;
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *