Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to add a custom Zipcode validator in checkout page Magento 2

12-18-2024

Add a custom Zipcode validator

In Magento 2, it’s not difficult to customize zip code validation and or add a custom zipcode validator on the checkout page.

Magento uses Regular Expression (re) to check whether the entered zipcode/postcode is correct.

In this article, we will add our own expression to validate the zipcode.

In Magento default, all patterns are defined in this file:

vendor/magento/module-directory/etc/zip_codes.xml

To add your pattern, or customize zip code validation on the checkout page to suit a specific country, create a new zip_codes.xml inside your own module

Here’s an example:

I choose NL (Dutch language) and add the zip_codes.xml to Mageplaza\HelloWorld\etc folder

<?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="NL">
            <codes>
                <code id="pattern_1" active="true" example="1234 AB">^[0-9]{4}\s[a-zA-Z]{2}$</code>
                <code id="pattern_2" active="true" example="1234AB">^[0-9]{4}\s?[a-zA-Z]{2}$</code>
            </codes>
        </zip>
</config>

The pattern_2 is quite similar to the first one, except that it allows users to enter space character.
I leave 2 patterns there so that you can see the difference, when apply to your store, you can remove the first pattern, pattern_2 still covers cases from pattern_1.

Now time to flush cache and test your result. You will no longer see this warning

Ductch lang warning

That’s how you can add a custom zip code validator in the Magento 2 checkout page. I hope you have found a helpful tutorial

If you have any issue, feel free to leave a comment below, Mageplaza and Magento community are willing to help.

Thanks for reading!

x


    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services