User experience plays a vital role in the online shopping journey and makes the shopping journey smooth. One important way to interact with customers in online stores is through forms and to ensure the correct data of customers we are using validation to inform customers of their wrong action or wrong information. To add Custom Validation in Checkout Page Form Field is crucial.

This blog post talks about the way to add custom validation in Checkout Page Form Field. We will add custom validation in the Telephone field.

Follow the below steps to add custom validation:

Step 1: Define a custom validation rule to add custom validation in Checkout Page Form Field

Create requirejs-config.js file at CompanyName/Modulename/view/frontend directory

var config = {
    config: {
        mixins: {
            'Magento_Ui/js/lib/validation/validator': {
                'Companyname_Modulename/js/validator-mixin': true
            }
        }
    }
};

Step 2: Create a custom validation in Checkout Page Form

Create validator-mixin.js file at CompanyName/Modulename/view/frontend/web/js directory

define([
    'jquery',
    'moment'
], function ($, moment) {
    'use strict';

    return function (validator) {

        validator.addRule(
            'custom-validate-telephone',
            function (value, params) {                
                 var phoneno = /^\(?([0-9]{3})[-]\)?([0-9]{3}[-])?([0-9]{4})$/;

                if((value.match(phoneno))){
                    return true;
                }       
            },
            $.mage.__("Please enter phone number in form of 123-456-7890.")
        );
    return validator;
    };
});

Step 3: Create a plugin to define a validation rule in checkout page

Create a file di.xml at CompanyName/Modulename/etc directory

<?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\Checkout\Block\Checkout\LayoutProcessor">
        <plugin name="custom-phone-validation" type="Companyname\Modulename\Block\Checkout\LayoutProcessor"/>
    </type> 
</config>

Step 4: Apply the rule in the checkout page shipping and billing form field

Create file LayoutProcessor.php at CompanyName/Modulename/Block/Checkout directory

<?php
namespace Companyname\Modulename\Block\Checkout;
class LayoutProcessor
{
    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {
            /*For shipping address form*/

            $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
            ['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['telephone']['validation']['custom-validate-telephone'] = true;    
                   

            foreach ($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
            ['payment']['children']['payments-list']['children'] as $key => $payment) { 
                /* Telephone Billing Address */
                if (isset($payment['children']['form-fields']['children']['telephone'])) {
                    $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                            ['payment']['children']['payments-list']['children'][$key]['children']['form-fields']['children']
                ['telephone']['validation'] = ['required-entry' => true, 'custom-validate-telephone' => true];
                }
            }
          
        return $jsLayout;
    }
}

You can also use this validation rule in any form through data-validate=”{required:true, custom-validate-telephone:true}”

Step 5: Execute the command and check the result

Run the commands and refresh the page

php bin/magento setup:di:compile
php bin/magento cache:flush

Finally, you can check your validation on the checkout page.

Conclusion:

By adding the new validation rule helps users to interact with form UI and this is beyond the Magento native provides validation rules. Hope this blog has helped learn how to add custom validation in checkout fields.
Please like and share if you like this post, if you have a query then please write a comment in the below comment section.

Thanks,

5/5 - (1 vote)