在 Magento 2 中,自定义邮政编码验证和/或在结帐页面上添加自定义邮政编码验证器并不困难。

Magento 使用正则表达式 ( re) 检查输入的邮政编码是否正确。

在这篇文章中,我们将add our own expression to validate the zipcode.

在 Magento 默认情况下,所有模式都在此文件中定义:

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

要添加您的模式,或在结帐页面上自定义邮政编码验证以适合特定国家/地区,请在您自己的模块zip_codes.xml中创建一个新模式

这是一个例子:

我选择 NL(荷兰语)并将其添加zip_codes.xmlExample\HelloWorld\etc文件夹

<?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>

Pattern_2与第一个非常相似,只是允许用户输入空格字符。
我在那里留下了 2 个图案,以便您可以看到差异,当应用到您的商店时,您可以删除第一个图案,pattern_2 仍然覆盖 pattern_1 的情况。

现在是时候刷新缓存并测试结果了