2

Basically I am trying to add custom validation rule in existing street field of shipping address form Checkout in magento 2 where pobox should not be allowed. I tried using mixin with requirejs-config.js which works well as it gets called till (console.log(hello)) but I am not sure why my 'validate-street-part' is not getting called from layoutprocessor and adding 'validate-street-part' to (mage/validation.js). Any advise or suggestion would be appreciated.

\app\design\frontend\Vendor\Magento_Checkout\web\js\pobox-mixin.js

define([
    'jquery',
    'jquery/ui',
    'jquery/validate',
   'mage/translate'
], function ($) {
    "use strict";

    return function () {
        console.log("hello");
        $.validator.addMethod(
            'validate-street-part',
            function (v) {
                var pattern = /^([post]*)$/.test(v);
                console.log(pattern);
                if(!pattern){ 
                    console.log("return true");
                    return true;
                }else{
                    console.log("return false");
                    return false; 
                }
            },
            $.mage.__("Please note that we cannot ship to PO Boxes. Please enter a physical address.")
        );
    };
});

app\design\frontend\Vendor\Magento_Checkout\requirejs-config.js

var config = {
    config: {
        mixins: {
'mage/validation': {
                'Magento_Checkout/js/pobox-mixin' : true
            }
        }
    }
};

app\code\Vendor\Checkout\etc\di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

 <type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
        <plugin name="rewrite-street" type="Vendor\Checkout\Block\Checkout\LayoutProcessor" sortOrder="10"/>
    </type>

</config>

app\code\Vendor\Checkout\Block\Checkout\LayoutProcessor.php

<?php
namespace Vendor\Checkout\Block\Checkout;

class LayoutProcessor
{

    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {

        $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
        ['shippingAddress']['children']['shipping-address-fieldset']['children']['street']['validation']['validate-street-part'] = 1;

return $jsLayout;
    }
}

2 Answers 2

3

I think you have missed '[children]' after '[street]' and before '[validation]'. Also you can assign 'true' instead of '1' It should be like below

$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['street']['children']['validation']['validate-street-part'] = true;

If you have any confusion in array keys and values, you can log below array.

print_r($jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['street']);

Sample code for street validation

$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
                ['children']['shippingAddress']['children']['shipping-address-fieldset'] 
                ['children']['street'] = [
                    'component' => 'Magento_Ui/js/form/components/group',
                    'label' => __('Street Address'),
                    'required' => true,
                    'dataScope' => 'shippingAddress.street',
                    'provider' => 'checkoutProvider',
                    'sortOrder' => 4,
                    'type' => 'group',
                    'config' => [        
                        'template' => 'ui/group/group',
                        'additionalClasses' => 'street'
                    ],
                    'children' => [
                        [
                            'component' => 'Magento_Ui/js/form/element/abstract',
                            'config' => [
                                'customScope' => 'shippingAddress',
                                'template' => 'ui/form/field',
                                'elementTmpl' => 'ui/form/element/input'
                            ],
                            'dataScope' => '0',
                            'provider' => 'checkoutProvider',
                            'validation' => ['required-entry' => true, "min_text_len‌​gth" => 1, "max_text_length" => 255, "validate-street-part" => true],
                            'additionalClasses' => 'field',
                            'label' => __('Street 1')
                        ],
                        [
                            'component' => 'Magento_Ui/js/form/element/abstract',
                            'config' => [
                                'customScope' => 'shippingAddress',
                                'template' => 'ui/form/field',
                                'elementTmpl' => 'ui/form/element/input'
                            ],
                            'dataScope' => '1',
                            'provider' => 'checkoutProvider',
                            'validation' => ["min_text_len‌​gth" => 1, "max_text_length" => 255,"validate-street-part" => true],
                            'additionalClasses' => 'additional',
                            'label' => __('Street 2')
                        ]

                    ]];
1
  • I am also facing same issues. above code is not working for me. May 12, 2020 at 15:30
3

app\design\frontend\Vendor\Magento_Checkout\web\js\pobox-mixin.js

 define([  
        'Magento_Ui/js/lib/validation/validator',
        'jquery',
         'jquery/ui',
         'jquery/validate',
        'mage/translate',
    ], function (validator,$) {
        "use strict";

        return function () {

            validator.addRule(
            'validate-street-part',function(v){
                var pattern = /((((p[\s\.]?)\s?[o\s][\.]?)\s?)|(post\s?office\s?))((box|bin|b\.?)?\s?((num|number|no|#)\.?)?\s?\d+)/igm.test(v);

                if(!pattern){ 
                    return true;
                }else{
                    return false; 
                }
            },
            $.mage.__("Please note that we cannot ship to PO Boxes. Please enter a physical address.")
            );
        };
    });

In the previous code I was using addMethod I used addRule instead and passed validator. I added 'Magento_Ui/js/lib/validation/validator' which is really important because I assume validator was not defined in mixin so it was unable to read though I was having jquery/validate. Also I made sure the order of defining files in mixin at the top follows certain order as I have in my answer cause some functionality of validator might be overriding or there could be a case where rule will be added to the orginal validator and later create another validator for adding custom rule. And other change has been posted by @MathewLawrence which is valid for layout processor. Thanks for contributing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.