Update validation rule for customer address attribute in Magento 2

Validation rules for customer address attributes are stored in customer_eav_attribute table. Below is example of how to adjust a rule for specific attribute. Let’s say we want first name to be minimum 3 chars long. It is done via data patch.

<?php

declare(strict_types=1);

namespace Magento\Customer\Setup\Patch\Data;

use Magento\Customer\Setup\CustomerSetup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class UpdateCustomerAddressAttributeValidationRule implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    /**
     * @var CustomerSetupFactory
     */
    private $customerSetupFactory;

    /**
     * UpdateCustomerAddressAttributeValidationRule constructor.
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        CustomerSetupFactory $customerSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->customerSetupFactory = $customerSetupFactory;
    }

    /**
     * @inheritDoc
     */
    public function apply()
    {
        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
        $this->updateCustomerAddressAttributeValidationRule($customerSetup);

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * @inheritDoc
     */
    public static function getDependencies()
    {
        return [
            DefaultCustomerGroupsAndAttributes::class,
        ];
    }

    /**
     * Update customer address validation rule
     *
     * @param CustomerSetup $customerSetup
     *
     * @return void
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    private function updateCustomerAddressAttributeValidationRule($customerSetup)
    {
        $entityAttributes = [
            'customer_address' => [
                'firstname' => [
                    'validate_rules' => '{"max_text_length":255,"min_text_length":3}'
                ]
            ],
        ];

        $customerSetup->upgradeAttributes($entityAttributes);
    }
}