How to enable phone number validation in Magento 2?

Say, you want in Magento to get phone numbers of new users via the Magento 2 registration form. For this, go to Stores > Setting > Configuration, open the Customers tab, and click Customer Configuration. Then, open the Name and Address Options section, find the Show Telephone field, and set it to Optional or Required.

But if you want the system to check what values are entered in this field and accept only numbers from 0 to 9, you need to enable the Magento 2 validation. Let’s see how to do it without coding.

Method 1 for Magento Commerce

Magento 2 Commerce has built-in Customers Attributes feature. You can create new fields and add them to Customer Registration, Customer Account Edit, or Admin Checkout forms.

1. For this, go to Stores > Attributes > Customer and click Add New Attribute.

magento-commerce-customer-attribute

2. Fill in Default Label and Attribute Code to identify the attribute on the frontend and in the admin panel.
3. Then choose the Input Type and specify if the value is required.
4. If needed, enter the Default Value.
5. In the Input Validation field, choose what kind of data should be entered. For example, for phone number validation, set this field to Numeric Only. Thus, Magento 2 will require subscribers to use numbers from 0 to 9 in this field.
6. Specify Minimum and Maximum Text Length, and set the Input/Output Filter.
7. Next, complete the Customers Grid and Segment Properties

magento-commerce-customer-attribute-segment-properties


Choose Yes or No for the following fields:

  • Add to Column Options
  • Use in Filter Options 
  • Use in Search Options
  • Use in Customer Segment 

8. In the Storefront Properties section, set Show on Storefront to Yes to display this attribute on the frontend.

magento-commerce-customer-attribute-storefront-properties

9. Enter the Sort Order and choose forms, where you want to apply this field.
10. Then, go to the Manage Labels/Options tab and enter labels for all the store views.
11. Save the changes.

Method 2 for Magento Open Source

There’re no vanilla settings telephone validation in Magento 2 Open Source but you can add this functionality with this Customer Attributes extension. It validates not only telephone numbers but also:

  • Decimal number
  • CNPJ
  • CPF
  • RUT code
  • Nickname
  • Royalty card
  • And more.

Besides additional validation options, the extension has dependencies between attributes. You can display certain fields to specific customer groups only.

According to the statistics, you may find helpfull the following question about custom filters.

How can we help you?

Didn’t you find the answer to your question? We are always happy to help you out.