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

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

23 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

2 days ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

2 days ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

2 weeks ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago