6

In Magento 2, I want to make phone fields number validation, (eg in the checkout page) only accepts numbers (and not characters)?

3 Answers 3

10

To validate number you can use validate-number in your module checkout_index_index.xml file.

Like ::

<item name="telephone" xsi:type="array">
    <item name="config" xsi:type="array">
    <item name="tooltip" xsi:type="array">
        <item name="description" xsi:type="string" translate="true">For delivery questions</item>
    </item>
    </item>
    <item name="validation" xsi:type="array">
        <item name="min_text_length" xsi:type="number">10</item>
        <item name="max_text_length" xsi:type="number">10</item>
        <item name="validate-number" xsi:type="number">0</item>
    </item>
</item>
3
  • 1
    Thanks this is working only for billing address can you suggest what i can do for shipping address Apr 21, 2020 at 7:53
  • Also, validate-number allows hyphen (-) in the beginning
    – GenZ Dev
    Oct 28, 2020 at 8:14
  • 1
    yes right, with billing address its working fine but with shipping address its not working. any suggestion? Feb 16, 2021 at 11:37
9

form should be like

<form class="form contact"
  action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
  id="contact-form"
  method="post"
  data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
  data-mage-init='{"validation":{}}'>

now in input field use data-validate="{'validate-number':true}"

Your input would look like

<input type="text" data-validate="{'validate-number':true}">

hope it helps.

0
4

You have to do add data-mage-init='{"validation":{}}' inside form declaration as following:

<form class="form contact"
      action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
      id="contact-form"
      method="post"
      data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
      data-mage-init='{"validation":{}}'>

Use class validate-number

I hope it will help you.

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.