How To

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!

Click to rate this post!
[Total: 2 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

22 hours ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

22 hours ago

Magento 2: How to Add Header and Footer in Checkout

Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…

2 days ago

Understanding Flexbox Layout in React Native

Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…

4 days ago

HYVÄ Themes Releases: 1.3.6 & 1.3.7 – What’s New

We're thrilled to announce the release of Hyvä Themes 1.3.6 and 1.3.7! These latest updates…

4 days ago

How Modern E-Commerce Platforms Leverage Docker & Kubernetes for Scalability

Your e-commerce platform is surging - orders are rolling in, traffic spikes are becoming the…

5 days ago