How to create custom input mask for zip code in Magento2?

When a customer specifies the country and zip code in the shipping address during checkout or shopping cart, Magento checks if the format of the entered code is valid for the specified country. This validation is implemented using the input masks for the zip code input field.

You can check all the input mask for zip in the below file:

<Magento_Directory_module_dir>/etc/zip_codes.xml. Now, Let’s learn the basic steps to add input mask for your country:

  1. Create a zip_codes.xml in app/code/Vendor/Module/etc.
  2. The content of the file should be similar to the following example:
<?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">

    <!-- Specify the country ISO code-->
    <zip countryCode="IN">
        <!-- You can specify several patterns for one country -->
        <codes>
            <code id="pattern_1" active="true" example="123456">^[0-9]{6}$</code>
        </codes>
    </zip>
</config>

You can define several zip code patterns for the same country, by passing a list of codes.

Remove a mask

To remove a mask, in your zip_codes.xml add the corresponding node and set active attribute to false.

We hope it will help you. Thank you!!

If any issue or doubt please feel free to mention in comment section.

We would be happy to help. Happy Coding!!


Source link