magento 2 restrict phone number field in admin panel

You want to restrict phone number field and it should accept only 10 digits number then need to create custom validator addRule.

I have created custom module with custom validator rule for make custom Phone Number validation.

File path: magento/app/code/Vendor/PhonenumverValidation/registration.php

<?php
use MagentoFrameworkComponentComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_PhonenumverValidation', __DIR__);

File path: magento/app/code/Vendor/PhonenumverValidation/etc/module.xml

<?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="Vendor_PhonenumverValidation" />
</config>

File path: magento/app/code/Vendor/PhonenumverValidation/view/adminhtml/web/js/validation-custom.js

require([
    'Magento_Ui/js/lib/validation/validator',
    'jquery',
    'mage/translate'
], function(validator, $){
    validator.addRule(
        'phonenumber-tendigit',
        function (value) {
            return value.length > 9 &&  value.length < 11 && value.match(/^d{10}$/);
        },
        $.mage.__('Please specify a valid 10 digits mobile number')
    );
});

File path: magento/app/code/Vendor/PhonenumverValidation/view/adminhtml/ui_component/customer_address_form.xml

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd" component="Magento_Customer/js/form/components/form">
    <fieldset name="general">
        <field name="telephone" sortOrder="130" formElement="input">
            <settings>
                <dataType>text</dataType>
                <visible>true</visible>
                <label translate="true">Phone Number</label>
                <validation>
                    <rule name="phonenumber-tendigit" xsi:type="boolean">true</rule>
                </validation>
            </settings>
        </field>
    </fieldset>
</form>

File path: magento/app/code/Vendor/PhonenumverValidation/view/adminhtml/layout/customer_index_edit.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="Vendor_PhonenumverValidation::js/validation-custom.js"/>
    </head>
</page>

Leave a comment

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