Magento2 Checkout – How to Validate Zip Code Field

checkoutmagento2uservalidation

I try to apply validation for postal code on checkout like 4 numbers and 2 characters(A-Z) ex: "9999AA".

Now, by default, if I press an invalid postal code on checkout page, I receive a message likes the screen-shot below:enter image description here But even If I don't change the postal code, I press next and finish my order.
Does anyone know how to solve this problem?
I found this link for javascript validation in magento 2 magento2 validator but I don't know where I can apply this validation validate-zip-international and then to modify this validation rule base on my format.
Or is there another way to create a validation rule on zip code?

Best Answer

To add validation on the zip field we should overwirte Magento_Checkout/layout/checkout_index_index.xml and add this code :

   <item name="validation" xsi:type="array">
        <item name="validate-zip-us" xsi:type="string">true</item>
    </item>

Like this

<item name="postcode" xsi:type="array">
    <item name="sortOrder" xsi:type="string">75</item>
        <!-- post-code field has custom UI component -->
    <item name="component" xsi:type="string">Magento_Ui/js/form/element/post-code</item>
    <item name="validation" xsi:type="array">
      <item name="required-entry" xsi:type="string">true</item>
      <item name="validate-zip-us" xsi:type="string">true</item>
    </item>
</item>

zip-range for example is a already defined rule in rules.js.

We can overwrite this rule or we can create another rule according to our needs in this location:Theme\Theme\Magento_Ui\web\js\lib\validation\rules.js >