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

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

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') ); } });

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

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

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.

And replace with this script.

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!

[Total: 12   Average: 4.7/5]