How To

How to perform custom validation in Magento 2

Every Business is different, that’s why each business has its own requirements. Being featured pack CMS, Magento allows the store owner to customize the way they can fulfill their business needs. Default, Magento allows you to build custom Extensions, CMS pages, block file and so on by giving freedom to give a personalized touch to your Store Layout. But sometimes, you need to set custom validation according to fulfill the business need for serving personalized experience or to comply with business requirements. Recently, we came across a requirement where the store admin was willing to add custom validation on Postcode the way customers can only enter 6 digits pin code not a bit small not a bit long. To do the same first we need to create a custom extension to perform JavaScript validation.
So, here is another blog series on “How to perform Custom Validation in Magento 2.”

First, we need to create registration.php file here at the following path.
app\code\vendor\extension\registration.php

<pre class="lang:default decode:true">
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'VENDOR_EXTENSION',
    __DIR__
);
</pre>

Now, we need to create module.xml file at below location.
app\code\vendor\extension\etc\module.xml

<pre class="lang:default decode:true">
<?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_EXTENSION" setup_version="1.0.0">
    </module>
</config>
</pre>

Create mcvalidation.js file here
app\code\vendor\extension\view\frontend\web\js\mcvalidation.js

define([
   'Magento_Ui/js/lib/validation/validator',
   'jquery',
   'jquery/ui',
   'jquery/validate',
   'mage/translate'
], function(validator,$){ 
    'use strict';

    return function() {
        $.validator.addMethod(
        'mcpostcode', function (value, element) { 
         return value.length > 5 &&  value.length < 7 && value.match(/[0-9]/);
        }, $.mage.__('Input 6 digit postcode')); 

        validator.addRule(
        'mcpostcode', function (value, element) { 
         return value.length > 5 &&  value.length < 7 && value.match(/[0-9]/);
        },$.mage.__('Input 6 digit postcode')
        );
    }
});
</pre>

We need to create requirejs-config.js file inside our extension folder.
app\code\vendor\extension\view\frontend\requirejs-config.js

var config = {
    "map": {
       "*": {
           "mcvalidation": "VENDOR_EXTENSION/js/mcvalidation"
       }
   }
};

Now its time to implement postcode validation rule to out checkout and for that purpose we need to create checkout_index_index.xml file at below location.
app\code\VENDOR\EXTENSION\view\frontend\layout\checkout_index_index.xml

<pre class="lang:default decode:true">
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="checkout" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <referenceBlock name="checkout.root">
                <arguments>
                    <argument name="jsLayout" xsi:type="array">
                        <item name="components" xsi:type="array">
                            <item name="checkout" xsi:type="array">                               
                                <item name="children" xsi:type="array">                           
                                    <item name="steps" xsi:type="array">
                                        <item name="children" xsi:type="array">
                                            <item name="shipping-step" xsi:type="array">
                                                <item name="children" xsi:type="array">
                                                    <item name="shippingAddress" xsi:type="array">
                                                        <item name="children" xsi:type="array">
                                                            <item name="shipping-address-fieldset" xsi:type="array"> 
                                                                <item name="children" xsi:type="array">                          
                                                                    <item name="postcode" xsi:type="array">
                                                                        <item name="validation" xsi:type="array">
                                                                            <item name="validate-digits" xsi:type="string">true</item>
                                                                            <item name="mcpostcode" xsi:type="string">true</item>     
                                                                        </item>
                                                                    </item>               
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>                                            
                                        </item>
                                    </item>                                    
                                </item>
                            </item>                            
                        </item>
                    </argument>
                </arguments>
            </referenceBlock>
        </referenceContainer>
    </body>
</page>
</pre>

 

Lastly, we need to replace script in onepage.phtml file located at below location. app\design\frontend\VENDOR\THEME\Magento_Checkout\templates\onepage.phtml
Search for the following script.

<pre class="lang:default decode:true">
<script type="text/x-magento-init">
{            
    "#checkout": {
        "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>
    }
}
</script>
</pre>

And replace with this script.

<pre class="lang:default decode:true">
<script type="text/x-magento-init">
    {
        "#checkout": {
            "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>
        },
        "*": {
            "VENDOR_EXTENSION/js/mcvalidation" : {}
        }
    }
</script>
</pre>

That’s it, hope this code will help you to add your Custom postcode validation in checkout field inside your Magento 2 store.

You can even use & customize this code according to your need adding different types of customization to your store checkout.

Let us know if you are facing an issue while implementing using this code.

Happy Coding!

Click to rate this post!
[Total: 15 Average: 4.3]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

3 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago