How do i add validation of maximum 30 alphabets allowed to shipping address form field in checkout page magento 2 ? https://prnt.sc/rz0n58
1 Answer
To change the validation of the for shipping address you need to create after plugin for jsLayout.
check below example to resolve your issue.
Step 1. Create Magento 2 module
Step 2. declare plugin in vendorname/modulename/etc/frontend/di.xml file
vendorname/modulename/etc/frontend/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\Onepage">
<plugin name="checkout_modification" type="vendorname\modulename\Plugin\AfterJsConfig"/>
</type>
</config>
Step 3: Create Plugin file to modify JsLayout and return it back to checkout page.
vendorname/modulename/Plugin/AfterJsConfig.php
<?php
namespace vendorname\modulename\Plugin;
use Magento\Checkout\Block\Onepage;
use Magento\Framework\Serialize\Serializer\Json;
class AfterJsConfig
{
/**
* @var Json
*/
protected $serializer;
/**
* AfterJsConfig constructor.
* @param Json $serializer
*/
public function __construct(
Json $serializer
) {
$this->serializer = $serializer;
}
/**
* @param Onepage $subject
* @param $result
* @return mixed
*/
public function afterGetJsLayout(Onepage $subject, $result) {
try {
if ($result != "") {
$jsonLayoutArray = $this->serializer->unserialize($result);
// you can add more modification here.
$jsonLayoutArray['components']['checkout']['children']['steps']['children']['shipping-step']
['children']['shippingAddress']['children']['shipping-address-fieldset']
['children']['street']['children'][0]['config']['validation']['max_text_length'] = 30;
return $this->serializer->serialize($jsonLayoutArray);
}
} catch (\Exception $e) {
}
return $result;
}
}
Hope this solution help you to complete you task.
Note: Please make it right and add plus to this solution if this solution work for you.
Thank you
-
I have added plugin because street address fields are not override by using xml. Apr 15, 2020 at 5:54
-
Will it work for "Address line 1 & 2 field" in shipping address ? Apr 15, 2020 at 6:26
-
1you can add it for address line one as well as two also. only you need to modify the array and add changes as per your requirements. also you can add your additional validation also. Apr 15, 2020 at 6:29
-
1To modify label for shipping address you can use below code. $jsonLayoutArray['components']['checkout']['children']['steps']['children']['shipping-step'] ['children']['shippingAddress']['children']['shipping-address-fieldset'] ['children']['street']['label'] = ""label"; Apr 18, 2020 at 11:05
-
1