0

Magento2 On contact Us page how can we validate phone nunber to accept only UK numbers?

3 Answers 3

1

You can add validation for UK numbers directly to phtml.

Override /vendor/magento/module-contact/view/frontend/templates/form.phtml in your theme/module and add

data-validate="{'phoneUK':true}"

/var/www/html/magento2/magento241/vendor/magento/module-contact/view/frontend/templates/form.phtml

0

Can you please check this link I think this may be helpful for you :

UI form validation in Magento 2

May be you need to add custom rule, this link may help you for this :

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

0

In your theme, navigate to app/design/frontend/YourVendor/YourTheme/Magento_Contact/layout/contact_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="contactForm">
            <action method="setValidation" ifconfig="contact/contact/enabled">
                <argument name="phone" xsi:type="string">true</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Next, you'll need to add custom JavaScript to enforce the UK phone number validation.

Create a JavaScript file at app/design/frontend/YourVendor/YourTheme/Magento_Contact/web/js/custom-validation.js

require([
    'jquery',
    'jquery/ui',
    'mage/validation'
], function($){
    $.validator.addMethod(
        'uk-phone',
        function (value, element) {
            return this.optional(element) || /^(\+?44|0)[\d]{10}$/.test(value);
        },
        $.mage.__('Please specify a valid UK phone number (e.g., +441234567890 or 01234567890).')
    );

    $('.contact-form').validate({
        rules: {
            telephone: {
                required: true,
                uk-phone: true
            }
        }
    });
});

In the same contact_index_index.xml file, require your JavaScript file.

<head>
    <script src="Magento_Contact::js/custom-validation.js"/>
</head>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.