Method to add custom JS validation rule in Magento 2

Add requirejs-config.js file to the following location:

app/code/[Vendor]/[Module]/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            "Magento_Ui/js/lib/validation/rules": "Vendor_Module/js/lib/validation/rules"
        }
    }
};

Copy file vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js

to

app/code/[Vendor]/[Module]/view/frontend/web/js/lib/validation/rules.js

Where you can add the custom validation code as following:

'validate-indian-zip-code-format': [
        function (value, param) {
            return /^[0-9]{6}$/.test(value);
        },
        $.mage.__('Please enter 6 Digits')
    ]


That’s it.

Overriding the inbuilt JS also done in the same,if you are using a custom , create a folder with the same naming pattern in the vendor folder structure and paste the file.

For overriding the js in the design folder it can simply done by pasting the js to web folder inside the Theme folder.

Leave a comment

Your email address will not be published. Required fields are marked *