Magento 2: How to validate phone number by their country?

alidation rules are written in validation.js (lib/web/mage/validation.js), so you need override it. requirejs-config.js

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

rules.js: add rule like this but for countries you want to check.

'phoneUK': [
            function (value) {
                return utils.isEmpty(value) || value.length > 9 &&
                    value.match(/^((?(0|+44)[1-9]{1}d{1,4}?)?s?d{3,4}s?d{3,4})$/);
            },
            $.mage.__('Please specify a valid phone number')
        ],

Referencec Url: https://www.bitbull.it/en/blog/custom-js-validation-magento2/

  • You can add your custom rule.

Leave a comment

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