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. 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; } }