Skip to content

Magento2.4.6: Why Custom validation rule not working anymore?

In the previous Magento version, it was working
Here is the code

PyarayCheckoutPluginCheckoutLayoutProcessorPlugin.php

<?php declare(strict_types=1);
 
namespace PyarayCheckoutPluginCheckout;

use MagentoCheckoutBlockCheckoutLayoutProcessor;
use PyarayCheckoutHelperData;

class LayoutProcessorPlugin
{
    private Data $helper;
    public function __construct(
        Data $helper
    ) {
        $this->helper = $helper;
    }

    public function afterProcess(LayoutProcessor $subject, array $result): array
    {
        if ($this->helper->isAllowed()) {
            $this->extendAddressFields($result['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']);
        }
        return $result;
    }

    protected function extendAddressFields(array &$jsLayout)
    {
        $jsLayout['street']['children'][0]['validation']['validate-custom-logic'] = true;
        $jsLayout['street']['children'][1]['validation']['validate-custom-logic'] = true;
    }
}

Pyaray/Checkout/view/frontend/requirejs-config.js

let config = {
    "config": {
        "mixins": {
            'Magento_Ui/js/lib/validation/validator': {
                'Pyaray_Checkout/js/validator-mixin': true
            }
        }
    }
};

Pyaray/Checkout/view/frontend/web/js/validator-mixin.js

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

    return function (validator) {
        validator.addRule('validate-custom-logic', function (v, e) {
            return /^*((#d+)|((box|bin)[-. /\]?d+)|(.*p[ .]? ?(o)[-. /\]?*-?((box|bin)|b|(#|n|num|number)?d+))|(p(ost|ostal)?*(o(ff(ice)?)?)?*((box|bin)|b)? d+)|(p *-?/?(o)?*-?box)|post*|((box|bin)|b) *(#|n|num|number)?*d+|(#|n|num|number) *d+)/i.test(v) === false;
        }, $.mage.__("We are unable to ship to PO Box"));

        return validator;
    };
});

Here is the checkout street field without validation.
this is checkout street field inspecton screenshot