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

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.

All patterns are defined in this file vendor/magento/module-directory/etc/zip_codes.xml

To add your pattern, create a new zip_codes.xml inside your own module
Here I choose NL (Dutch language) and add the zip_codes.xml to Mageplaza\HelloWorld\etc folder

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Directory:etc/zip_codes.xsd">
    <zip countryCode="NL">
                <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>

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

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

Enjoyed the tutorial? Spread it to your friends!

People also searched for

  • custom zipcode validator
  • validate zipcode checkout Magento 2
  • space Dutch zipcode
  • 2.2.x, 2.3.x, 2.4.x