3

Magento Version : 2.3.1

I want to apply custom validation on the custom field of the checkout shipping form.

Please suggest to me, how can achieve this?

Thanks in advance.

1 Answer 1

2

1. Create custom JS validator

app/code/Acme/StackExchange/view/frontend/requirejs-config.js

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

app/code/Acme/StackExchange/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) { // your logic here return true; }, $.mage.__("Please enter a valid ...")); return validator; }; }); 

2. Set validator to related fields with jsLayout

app/code/Acme/StackExchange/etc/frontend/di.xml

<?xml version="1.0" encoding="UTF-8"?> <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="Acme_StackExchange_Plugin_Checkout_LayoutProcessorPlugin" sortOrder="10" type="Acme\StackExchange\Plugin\Checkout\LayoutProcessorPlugin"/> </type> </config> 

app/code/Acme/StackExchange/Plugin/Checkout/LayoutProcessorPlugin.php

<?php declare(strict_types=1); namespace Acme\StackExchange\Plugin\Checkout; use Magento\Checkout\Block\Checkout\LayoutProcessor; class LayoutProcessorPlugin { /** * @param LayoutProcessor $subject * @param array $result * @param array $jsLayout * @return array */ public function afterProcess( LayoutProcessor $subject, array $result ): array { // extend shipping address form $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['YOUR_FIELD']['validation']['validate-custom-logic'] = true; } } 
3
  • Thanks @Victor Tihonchuk I used your solution and it's works well Commented Jun 10, 2022 at 11:24
  • What we need to put on YOUR_FIELD? Commented Dec 2, 2022 at 8:41
  • 1
    @LucasD.A.W. <YOUR_FIELD> means form field name in that you need to put validation. Commented Dec 5, 2022 at 11:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.