How to Add Custom Input Mask for ZIP Code in Magento 2
Magento 2 is a globally accepted and popular CMS used by merchants around the world to offer their products and services online. The platform offers the insane capability to customize the default features in order to prepare the store for a specific audience or global customers.
Today, I’ll talk about one such solution to customize the store’s zip code validation for country-specific customers.
The admin can add a custom zip code validator to the checkout page in Magento 2 store based on the countries they serve.
For example, the zip code example shown in the default message on the checkout page is the numeric value “12345”. However, countries like the Netherlands contain alphanumeric zip codes.
Hence, follow the below solution to add custom input mask for ZIP code in Magento 2 store to show the example in alphanumeric format or any other validations based on the zip code format.
Method to Add Custom Input Mask for ZIP Code in Magento 2:
Create zip_codes.xml at app/code/Vendor/Module/etc/zip_codes.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Directory:etc/zip_codes.xsd"> <zip countryCode="GG"> <codes> <code id="pattern_1" active="true" example="AB1 2CD">^[a-zA-Z]{2}[0-9]{1}\s[0-9]{1}[a-zA-Z]{2}$</code> </codes> </zip> <zip countryCode="NL"> <codes> <code id="pattern_1" active="true" example="1234BW">^[0-9]{4}[a-zA-Z]{2}$</code> <code id="pattern_2" active="true" example="1234 BW">^[0-5]{4}[a-z]{2}$</code> </codes> </zip> </config> |
That’s it.
Any doubts about zip code validation in Magento 2? If yes, do mention them in the Comments section below. I’d be happy to help. If you want to check delivery availability based on zip codes and restrict orders for invalid zip codes then explore our Magento 2 Restrict Zip Codes Extension.
Also, do share the post with Magento Community via social media.
Thank you.
Chandresh Chauhan
He has been with Meetanshi for more than three years now as a certified Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.
Prev
How to Display Simple Product Image for Configurable Product Image in Magento 2 Mini Cart and Cart
How to Add Google reCAPTCHA to Magento 2
Next