How to add Custom Validation to checkout fields in Magento 2?

User experience plays an important role throughout the buying journey in online shopping. The store must be designed in a way that it responds to every touchpoint seamlessly. One of the important ways of interacting with a customer in an online store is through Forms. Validations in the forms help make the interactions and the journey smooth. 

This blog talks about the way to add validation in checkout fields.

Follow the below steps to validate checkout fields:

Step 1:

  • Since we want to make changes in the checkout section, we can do so by overriding/extending LayoutProcessor.
  • That can be done in the below-given process:
  • Create a LayoutProcessor file in your module:

<?php

namespace YVendor\NewMod\Block;

class LayoutProcessor
{
/**
* @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
* @param array $jsLayout
* @return array
*/
public function afterProcess(
\Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
array $jsLayout
) {
// City
$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['city']['validation']['validate-name'] = true;

return $jsLayout;
}
}

  • Here validate-name is a custom validation rule

Step 2:

  • Add this LayoutProcessor plugin in the di.xml file in your module like below:

<?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="YVendor_NewMod_CheckoutValidation" type="YVendor_NewMod_CheckoutValidation" sortOrder="100"/>
</type>
</config>

Step 3:

  • To work out our custom validation rule, we need to add this ‘validate-name’ rule in existing rules which is in vendor\magento\module-ui\view\base\web\js\lib\validation\rules.js
  • We can do so, by overriding that js file in our module like below way:

Create rules.js file in your module:

define([
'jquery',
'underscore',
'./utils',
'moment',
'tinycolor',
'jquery/validate',
'mage/translate'
], function ($, _, utils, moment, tinycolor) {
'use strict';

return _.mapObject({
'validate-name': [
function (value, params) {
return utils.isEmpty(value) || /^[a-zA-Z ]*$/.test(value)
},
$.mage.__('City name should contain alphabets and spaces only.')
]
}, function (data) {
return {
handler: data[0],
message: data[1]
};
});
});

- Now create utils.js file as below:
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

/**
* @api
*/
define(function () {
'use strict';

var utils = {
/**
* Check if string is empty with trim.
*
* @param {String} value
* @return {Boolean}
*/
isEmpty: function (value) {
return value === '' || value == null || value.length === 0 || /^\s+$/.test(value);
},
};
return utils;
});

Step 4: Run the below commands:

  • php bin/magento s:up
  • php bin/magento s:s:d –f
  • php bin/magento c:f

Step 5: See Output:

Conclusion

Adding the validations ensures that the users get the appropriate feedback to follow the journey further. Thus, making the journey user-friendly and seamless. Hope this blog has helped learn how to add custom validation in checkout fields. 

Check out our store to learn about the extensions and plugins designed by us to make it quicker and easier for you to develop an application and reach out to us to learn more about eCommerce development. 

This blog is written by Yash Bhimjiyani, Magento Developer at Tridhya Innovation 

Leave a Reply

Your email address will not be published. Required fields are marked *