Magento, Magento 2

How to Add Phone Number Validation in Checkout in Magento 2

How to Add Phone Number Validation in Checkout in Magento 2

In this tutorial, Today I will explain to how to add phone number validation in checkout page in Magento 2. On checkout page, There are many fields available. By default in phone number, You can add any of string value and number value.

But, now if you want to allow only number then, you need to add validation rule on phone number field. So, let’s follow the below steps to add validation on checkout page.

You may also like this :

1) First of all, Let’s assume that you have a simple module. Now, you need to create di.xml file at app/code/RH/Helloworld/etc/frontend/ and paste the below code to add plugin :

<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Block\Checkout\AttributeMerger">
        <plugin name="rh_checkout_phone_number"
                type="RH\Helloworld\Plugin\Block\Checkout\PhonePlugin" sortOrder="10"/>
    </type>
</config>

2) Now, Create PhonePlugin.php file at app/code/RH/Helloworld/Plugin/Block/Checkout/ and paste the below code to add validation code :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Plugin\Block\Checkout;

use Magento\Checkout\Block\Checkout\AttributeMerger;

class PhonePlugin
{
    /**
     * @param AttributeMerger $subject
     * @param $result
     * @return mixed
     */
    public function afterMerge(AttributeMerger $subject, $result)
    {
        $result['telephone']['validation'] = [
            'required-entry'  => true,
            'max_text_length' => 10,
            'validate-number' => true
        ];
        return $result;
    }
}

Here, I added 3 rule in phone number field. 1) Required Entry 2) Max Text Length 3) Input Validation.

Now, Just clean cache and check it on checkout page.

That’s it !!!

I hope this blog is easy to understand how to add phone number validation in checkout page in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with a proper solution.

Stay Safe and Stay Connected !!

Tagged , ,