Magento2 On contact Us page how can we validate phone nunber to accept only UK numbers?
3 Answers
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}"
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 :
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>