Custom validation for Phone number in Magento 2
-
14-04-2021 - |
Pregunta
I have created the custom validation method to validate telephone number to accept only numbers and (- symbols. It's working when I tried with JavaScript in HTML page but not working when applied to Magneto 2.3.3-p1.
For this I have tried the below code to rules.js from /root/html/vendor/magento/module-ui/view/base/web/js/lib/validation.
'phone_number_checkout': [
function (value) {
return utils.isEmptyNoTrim(value) || /^[0-9-]/.test(value);
},
$.mage.__('Please enter a valid phone number. For example 123-(456)-(7890) or 123-456-7890 or 1234567890.')
]
and validation rule added to layout checkout_index_index.xml file as below
<?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="checkout.root">
<arguments>
<argument name="jsLayout" xsi:type="array">
<item name="components" xsi:type="array">
<item name="checkout" xsi:type="array">
<item name="children" xsi:type="array">
<item name="steps" xsi:type="array">
<item name="children" xsi:type="array">
<item name="shipping-step" xsi:type="array">
<item name="children" xsi:type="array">
<item name="shippingAddress" xsi:type="array">
<item name="children" xsi:type="array">
<item name="shipping-address-fieldset" xsi:type="array">
<item name="children" xsi:type="array">
<item name="telephone" xsi:type="array">
<item name="validation" xsi:type="array">
<item name="min_text_length" xsi:type="number">0</item>
<item name="max_text_length" xsi:type="number">30</item>
<item name="phone_number_checkout" xsi:type="boolean">true</item>
<item name="required-entry" xsi:type="boolean">true</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</argument>
</arguments>
</referenceBlock>
</body>
</page>
Is my validation rule is correct? If it's wrong procedure please guide me.
Any suggestion?
Solución
Achieved by adding below validation rule to rules.js file from root/html/app/design/XXX/XXX/Magento_Ui/web/js/lib/validation/
'phone_number_client': [
function (value){
return value.match(/^([0-9\(\)\/\\-]*)$/);
},
$.mage.__('Please enter a valid phone number. For example (123)456-(7890) or 123-456-7890.')
]
The above validation will allow only numbers, hyphens(-) and brackets(()).
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange