Site icon MageComp Blog

How to perform custom validation in Magento 2

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!

Exit mobile version