Let’s add custom validation rules at checkout.
We have added custom validation before placing the order on the checkout page. However, we can restrict address-level fields to shipping and billing addresses by adding default and custom UI validation.
This post will add a custom rule to the Knockout validation rules on checkout. After that, we will override Magento Ui using the mixin method.
We can use Mixin by creating the file requirejs-config.js. Then, we can create a mixin in theme and custom modules. We will do this in a custom module in this post.
So let’s check out how to add a custom validation rule in Knockout Validation Rules on the checkout.
Magento 2: Add Custom Validation Rules on Checkout
Firstly, we must create requirejs-config.js in the frontend area of our module. We need requirejs-config.js to define a mixin for the validator class of the Magento_Ui module.
/**
* @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
*/
var config = {
config: {
'mixins': {
'Magento_Ui/js/lib/validation/validator': {
'Vendor_Module/js/lib/validation/validator-mixin':true
}
}
}
};
It’s time to create a mixin file with the name validator-mixing.js on the path defined in requirejs-config.js.
We need validator-mixing.js to add custom rules to the knockout rules. We will define the logic of validation in this file.
/**
* @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
*/
define([
'jquery',
], function ($) {
'use strict';
return function (validator) {
validator.addRule(
'rule_name',
function (value) {
// validation logic
$isValid = false; //logic to validation
if($isValid) {
return true;
}
return false;
},
$.mage.__("Validation Message")
);
return validator;
};
});
That’s it. Adding custom validation rules to the checkout rules is pretty straightforward.
Let’s check out a real-world example. First, we will add PO box address validation to the street address of the shipping and billing addresses.
Magento 2: Add PO box validation on shipping and billing addresses.
As we have already placed validation before the place order button. By using knockout validation rules, we will restrict addresses with PO Box No. in the shipping and billing addresses.
As mentioned, let’s create requirejs-config.js to create a mixin.
/**
* @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
*/
var config = {
config: {
'mixins': {
'Magento_Ui/js/lib/validation/validator': {
'SbDevBlog_Checkout/js/lib/validation/validator-mixin':true
}
}
}
};
Now, let’s create a validator-mixin.js file in the mentioned path.
/**
* @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
*/
define([
'jquery',
], function ($) {
'use strict';
return function (validator) {
validator.addRule(
'pobox-validation',
function (value) {
let isValidPoBox = /((((p[\s\.]?)\s?[o\s][\.]?)\s?)|(post\s?office\s?)|(postal\s?)|(post\s?))((box|bin|b\.?)?\s?((num|number|no|#)\.?)?\s?\d+)/igm.test(value);
return !isValidPoBox;
},
$.mage.__("PO BOX address not allowed")
);
return validator;
};
});
We have added the Po Box address validation rule with the name pobox-validation
. We need to use it in the shipping and billing address field.
Let’s create a plugin on the LayoutProcessor block of Magento’s checkout module to bind custom validation to the shipping and billing addresses.
<?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="validate_pobox_Checkout" type="SbDevBlog\Checkout\Plugin\Block\LayoutProcessor" sortOrder="100"/>
</type>
</config>
Finally, we will create a plugin with the name LayoutProcessor in the mentioned path inside the above declaration of the plugin.
<?php
/**
* @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
*/
namespace SbDevBlog\Checkout\Plugin\Block;
use SbDevBlog\Checkout\Services\ValidationConfigurationService;
class LayoutProcessor
{
/**
* @var ValidationConfigurationService
*/
private ValidationConfigurationService $validationConfigurationService;
/**
* Constructor
*
* @param ValidationConfigurationService $validationConfigurationService
*/
public function __construct(
ValidationConfigurationService $validationConfigurationService
)
{
$this->validationConfigurationService = $validationConfigurationService;
}
/**
* Add POBOX Validation to street address on street address
*
* @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
* @param array $jsLayout
* @return array
*/
public function afterProcess(
\Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
array $jsLayout
)
{
if ($this->validationConfigurationService->getValidationStatus()) {
// PoBox Validation on street for shipping address
$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
['shippingAddress']['children']['shipping-address-fieldset']
['children']['street']['children'][0]['validation']['pobox-validation'] = true;
$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
['shippingAddress']['children']['shipping-address-fieldset']
['children']['street']['children'][1]['validation']['pobox-validation'] = true;
// PoBox Validation on street for billing address
if (isset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
['payment']['children']['payments-list']['children']
)) {
foreach ($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
['payment']['children']['payments-list']['children'] as $key => $payment) {
if (isset($payment['children']['form-fields']['children']['street'])) {
$jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
['payment']['children']['payments-list']['children'][$key]['children']['form-fields']['children']
['street']["children"][1]['validation']['pobox-validation'] = true;
$jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
['payment']['children']['payments-list']['children'][$key]['children']['form-fields']['children']
['street']["children"][0]['validation']['pobox-validation'] = true;
}
}
}
}
return $jsLayout;
}
}
That’s it. Thank you for reading this post on Magento 2: Add Custom Validation Rules on Checkout. Please subscribe to our blog and share it with your connections. Also, please use the comment box for your valuable feedback and suggestions.
Note: Please verify the code of this blog and the relevant git repository before using it in production.
🙂 HAPPY CODING 🙂