Magento

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.

Read related blog How to Add Sample File For Custom Entity Import Functionality in Magento 2

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:

namespace YVendor\NewMod\Block;

Explain

class LayoutProcessor
{
/**
* @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
* @param array $jsLayout

Explain

* @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:


http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

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:

Explain

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

Explain

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]
};
});
});

Explain

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

Explain

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

Explain

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:

shipping

 

 

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 TridhyaTech

Transform Your Business With Digital Enterprise Solutions

Contact us

Our Offices

AHMEDABAD, INDIA

401, One World West, Nr. Ambli T-Junction 200, S P Ring Road, Bopal, Ahmedabad, Gujarat 380058

UK

Kemp House 160 City Road, London, United Kingdom EC1V 2NX

GERMANY

Nürnberger Str. 46 90579 Langenzenn Deutschland

AUSTRALIA

Level 36 Riparian Plaza, 71 Eagle Street, Brisbane, QLD 4000

USA

4411 Suwanee Dam road, Bld. 300 Ste. 350 Suwanee GA, 30024

SOUTH AFRICA

Cube Work Space, 24 Hans Strijdom Avenue, Cape Town

Mahindra DUBAI, UAE

B 503 Sama Tower, Sheikh Zayed Road, United Arab Emirates

CANADA

34 Applegrove Ct. Brampton ON L6R 2Y8