How to set firstname and lastname with minimum two character in Magento 2?

Magento 2 First name and Last name is default customer entity available in Native Magento. Once you install Magento 2, Customer first name and last name attribute available.

Firstname and Lastname attribute available with Customer and Customer_address entity type.

customer entity type contains attribute used for registration page and customer form related entity.

customer_address entity types used for billing and shipping form of customer.

Our Main concern is, How we can limit customer first name and last name attribute length to a minimum of two characters. Default Magento contains one character length for both the attributes.

For a change the customer first name and last name entity with two characters we need to change customer_eav_attribute table with a validate_rules column for first name and last name attribute.

By default firstname and lastname attribute contains value for validate_rules column value as {“max_text_length”:255,”min_text_length”:1}.

We just need to change validate_rules column value to {“max_text_length”:255,”min_text_length”:2} for set minimum two character

1.  Server-side validation after form submit

Let’s create module name is Rbj_CustomerName where Rbj is Vendor name and CustomerName is the module name.
Our Module resides under app/code/Rbj/CustomerName location.

Path:  app/code/Rbj/CustomerName/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Rbj_CustomerName',
    __DIR__
);

Path: app/code/Rbj/CustomerName/etc/module.xml file,

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Rbj_CustomerName" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Customer" />
        </sequence>
    </module>
</config></pre>

Path: app/code/Rbj/CustomerName/Setup/UpgradeData.php

<?php

namespace Rbj\CustomerName\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;

class UpgradeData implements UpgradeDataInterface
{
    /**
     * @param EavSetup $eavSetupFactory
     */
    public function __construct(
        \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
    }

    /**
     * Upgrades customer_eav_attribute table for validate_rules to set limit on character for first and lastname
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $entityAttributes = [
            'customer_address' => [
                'firstname' => [
                    'validate_rules' => '{"max_text_length":255,"min_text_length":2}'
                ],
                'lastname' => [
                    'validate_rules' => '{"max_text_length":255,"min_text_length":2}'
                ],
            ],
            'customer' => [
                'firstname' => [
                    'validate_rules' => '{"max_text_length":255,"min_text_length":2}'
                ],
                'lastname' => [
                    'validate_rules' => '{"max_text_length":255,"min_text_length":2}'
                ],
            ],
        ];
        $this->upgradeAttributes($entityAttributes, $customerSetup);
        $setup->endSetup();
    }

    protected function upgradeAttributes(array $entityAttributes, \Magento\Customer\Setup\CustomerSetup $customerSetup)
    {
        foreach ($entityAttributes as $entityType => $attributes) {
            foreach ($attributes as $attributeCode => $attributeData) {
                $attribute = $customerSetup->getEavConfig()->getAttribute($entityType, $attributeCode);
                foreach ($attributeData as $key => $value) {
                    $attribute->setData($key, $value);
                }
                $attribute->save();
            }
        }
    }
}

Using the above script, validate_rules will be changed in customer_eav_attribute table and validation applied for server side.

Server side validation for firstname and last name attribute

2.  Client Side Validation (Before form submit)

Now Override the /vendor/magento/module-customer/view/frontend/templates/widget/name.phtml file for add validation to client side.

Add class for first name and last name input element with minimum-length-2 validate-length

Your Input with first name and last name look like below in name.phtml file,

Firstname input
<input type="text" id="<?= $block->escapeHtmlAttr($block->getFieldId('firstname')) ?>"
                       name="<?= $block->escapeHtmlAttr($block->getFieldName('firstname')) ?>"
                       value="<?= $block->escapeHtmlAttr($block->getObject()->getFirstname()) ?>"
                       title="<?= $block->escapeHtmlAttr($block->getStoreLabel('firstname')) ?>"
                       class="minimum-length-2 validate-length input-text <?= $block->escapeHtmlAttr($block->getAttributeValidationClass('firstname')) ?>" <?php if ($block->getAttributeValidationClass('firstname') == 'required-entry') echo ' data-validate="{required:true}"' ?>>

Last name input:
 <input type="text" id="<?= $block->escapeHtmlAttr($block->getFieldId('lastname')) ?>"
                       name="<?= $block->escapeHtmlAttr($block->getFieldName('lastname')) ?>"
                       value="<?= $block->escapeHtmlAttr($block->getObject()->getLastname()) ?>"
                       title="<?= $block->escapeHtmlAttr($block->getStoreLabel('lastname')) ?>"
                       class="minimum-length-2 validate-length input-text <?= $block->escapeHtmlAttr($block->getAttributeValidationClass('lastname')) ?>" <?php if ($block->getAttributeValidationClass('lastname') == 'required-entry') echo ' data-validate="{required:true}"' ?>>
Client-side validation for first name and last name attribute

When you add minimum-length-2 validate-length class to first name and last name input element, they do validation for client end before form submit.