0

I want to add validation to prevent code blocks or special characters like {}%.

enter image description here

2 Answers 2

2

Solution: To add custom validation on the checkout page, create a new JS mixin that extends Magento_Ui/js/lib/validation/validator and create a plugin for Magento\Checkout\Block\Checkout\LayoutProcessor to declare the validation rule.

Implementation: Assume you named the vendor name Vendor, and the module name Checkout (You can change the vendor name and module name as you wish). Take the following steps:

Step 1: Create the registration.php file:
File path: app/code/Vendor/Checkout/registration.php

<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_Checkout', __DIR__);

Step 2: Create the module.xml file:
File path: app/code/Vendor/Checkout/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Checkout">
        <sequence>
            <module name="Magento_Checkout"/>
            <module name="Magento_Ui"/>
        </sequence>
    </module>
</config>

Step 3: Create the requirejs-config.js file.
File path: app/code/Vendor/Checkout/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Ui/js/lib/validation/validator': {
                'Vendor_Checkout/js/form/element/validator-rules-mixin': true
            }
        }
    }
};

Step 4: Create the validator-rules-minxin.js file:

File path: app/code/Vendor/Checkout/view/frontend/web/js/form/element/validator-rules-mixin.js

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

    /**
     * Validate that string has specific special characters
     * @param {String} value
     * @return {Boolean}
     */
    function validateSpecialCharacters(value) {
        return /^[^{}%]+$/.test(value);
    }

    return function (validator) {
        validator.addRule(
            'validate-special-characters',
            function (value) {
                if ($.mage.isEmptyNoTrim(value)) {
                    return true;
                }

                return validateSpecialCharacters(value);
            },
            $.mage.__('Please remove invalid characters: {}%')
        );

        return validator;
    };
});

Step 5: Create di.xml file:
File path: 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="ModifyCheckoutField" type="Vendor\Checkout\Plugin\ModifyCheckoutField"/>
    </type>
</config>

Step 6: Create ModifyCheckoutField.php file.
File path: app/code/Vendor/Checkout/Plugin/ModifyCheckoutField.php

<?php
declare(strict_types=1);

namespace Vendor\Checkout\Plugin;

class ModifyCheckoutField
{
    /**
     * Modify checkout street field validation
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array $jsLayout
    ) {
        //Shipping Address
        if (isset(
            $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
            ['children']['shippingAddress']['children']['shipping-address-fieldset']['children']
        )) {
            $shippingAddressFieldset = &$jsLayout['components']['checkout']['children']['steps']['children']
            ['shipping-step']['children'] ['shippingAddress']['children']['shipping-address-fieldset']['children'];
            $shippingAddressFieldset = $this->addValidationForFields($shippingAddressFieldset);
        }

        //Billing Address on payment method
        if (isset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']
            ['children']['payment']['children']['payments-list']['children'])) {
            $paymentList = $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']
            ['children']['payment']['children']['payments-list']['children'];

            foreach ($paymentList as $key => $payment) {
                if (isset($payment['children']['form-fields']['children'])) {
                    $paymentsListFormFields = &$jsLayout['components']['checkout']['children']['steps']
                    ['children']['billing-step']['children']['payment']['children']['payments-list']
                    ['children'][$key]['children']['form-fields']['children'];
                    $paymentsListFormFields = $this->addValidationForFields($paymentsListFormFields);
                }
            }
        }

        //Billing Address on payment page
        if (isset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']
            ['children']['payment']['children']['afterMethods']['children'])) {
            if (isset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                ['payment']['children']['afterMethods']['children']['billing-address-form']['children']['form-fields']
                ['children'])) {
                $billingAddressFormFormFields = &$jsLayout['components']['checkout']['children']['steps']['children']
                ['billing-step']['children']['payment']['children']['afterMethods']
                ['children']['billing-address-form']['children']['form-fields']['children'];
                $billingAddressFormFormFields = $this->addValidationForFields($billingAddressFormFormFields);
            }
        }

        return $jsLayout;
    }

    /**
     * @param $formFields
     * @return array
     */
    private function addValidationForFields($formFields): array
    {
        $formFields['street']['children'][0]['validation']['validate-special-characters'] = true;
        $formFields['street']['children'][1]['validation']['validate-special-characters'] = true;
        $formFields['street']['children'][2]['validation']['validate-special-characters'] = true;

        return $formFields;
    }
}

Step 7: Finally, run the setup:upgrade command to make your new module active, and then compile code, deploy static content:

bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy -f

Done.

0

I have tried and Its not working. Validation class is not added to data bind and also any where.

Your Answer

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

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