How to Apply Validation on Backend Customer Custom Field in Magento 2

How to Apply Validation on Backend Customer Custom Field in Magento 2

Hello Magento Friends,

I am here with another solution for you, How to Apply Validation on Backend Customer Custom Field in Magento 2.

To fulfill orders in the best possible way and personalize the shopping experience, Magento store owners require additional information from customers. For this, you need to create a custom customer attribute. But it is also necessary to validate the input of custom customer attributes in order to avoid wrong information.

Here are the steps for How to Apply Validation on Backend Customer Custom Field in Magento 2.

Steps to Apply Validation on Backend Customer Custom Field in Magento 2:

Step 1:  First we need to create our custom customer attribute so we need to add the InstallData.php file in the following path

app\code\Vendor\Extension\Setup\InstallData.php

And add the below code

<?php
namespace Vendor\Extension\Setup;

use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    private $customerSetupFactory;

    public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory)
    {
        $this->customerSetupFactory = $customerSetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerSetup->addAttribute(Customer::ENTITY, 'custom_attribute_code', [
            'type' => 'varchar',
            'label' => 'Custom Attribute',
            'input' => 'text',
            'class' => '',
            'source' => '',
            'backend' => (\Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend::class),
            'required' => false,
            'sort_order' => 100,
            'system' => false,
            'visible' => true,
            'user_defined' => false,
            'searchable' => true,
            'filterable' => true,
            'comparable' => true,
            'frontend_class' => 'validate-zero-or-greater',
            'visible_on_front' => true,
            'unique' => false,
            'apply_to' => ''
        ]);

        // add attribute to form
        $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'custom_attribute_code');
        $used_in_forms[]="adminhtml_customer";
        $used_in_forms[]="checkout_register";
        $used_in_forms[]="customer_account_create";
        $used_in_forms[]="customer_account_edit";
        $used_in_forms[]="adminhtml_checkout";

        $attribute->setData('used_in_forms', $used_in_forms)
            ->setData("is_used_for_customer_segment", true)
            ->setData("is_system", 0)
            ->setData("is_user_defined", 1)
            ->setData("is_visible", 1)
            ->setData("sort_order", 100);
        $attribute->save();

        $setup->endSetup();
    }
}

Step 2: Now you need to create di.xml in the following path.

app\code\Vendor\Extension\etc\di.xml

Then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Ui\DataProvider\EavValidationRules">
        <plugin name="custom_attribute_validation" type="Vendor\Extension\Plugin\EavValidationRules" sortOrder="10" disabled="false"  />
    </type>
</config>

Step 3: Now you need to create EavValidationRules.php in the following path

app\code\Vendor\Extension\Plugin\EavValidationRules.php

And add the below code

<?php

namespace Vendor\Extension\Plugin;

class EavValidationRules
{
    public function afterBuild(\Magento\Ui\DataProvider\EavValidationRules $subject, $result, $attribute)
    {
        if($attribute->getAttributeCode() == "custom_attribute_code")
        {
            $validationClasses = explode(' ',$attribute->getFrontendClass());
            $rules = [];
            foreach ($validationClasses as $class)
            {
                $rules[$class] = true;
            }
            return $rules;
        }
    }
}

Conclusion:

Hence, this way you can Apply Validation on Backend Customer Custom Field in Magento 2.

Related Articles,

If you face any difficulty, share with me via the comment box and I will help you out with it. Share the article with your developer group. Stay in touch with us!

Happy Coding!

Previous Article

How to Add Dynamic CMS Block Programmatically in Magento 2

Next Article

How to Get Rid Of Non-used Product Images from Database of your Magento 2

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨