How to add custom validation to checkout


Magento 2, powered by Adobe Commerce, is an ecommerce platform that offers unmatched flexibility, allowing you to fully customize your online store. With the ability to fully customize your online store, you have the freedom to design it to your needs. But to truly elevate the checkout process within the Magento 2 (Adobe Commerce) framework, it's crucial to incorporate validation. By implementing custom validations, you have the liberty to tailor the rules to perfectly align with your business requirements, resulting in accurate data input and a seamless and satisfying checkout experience for your customers. 

Add a custom validation in Shipping step:

This article provides instructions on how to add a validation for the shipping step, during checkout. It allows you to display a customized message based on conditions. We will achieve this by employing a validateShippingInformation mixin. Additionally you can also utilize this mixin to validate custom fields besides shipping address and shipping method.

Below are the steps to follow for adding a custom validation:
Step 1: Create a new module  

Step 2: To create a mixin for ‘shipping-method-mixin.js’, you should first generate a ‘requirejs-config.js’ file in the  app/code/Vendor/Module/view/frontend directory with the following content:

var config = {
  config: {
     
mixins: {
          'Magento_Checkout/js/view/shipping': {
              'Vendor_Module/js/shipping-method-mixin': true
          }

Step 3: Create a shipping-method-mixin.js file in app/code/Vendor/Module/view/frontend/web/js directory

define([
  'Magento_Checkout/js/model/quote',
  'uiRegistry',
  'jquery',
  'Magento_Checkout/js/model/shipping-rate-service',
  'Magento_Ui/js/model/messageList'
], function (
  quote,
  registry,
  $,
  $t,
  globalMessageList
) {
  'use strict';
  return function (shipping, messageContainer) {
      messageContainer = messageContainer || globalMessageList;
      return shipping.extend({
          validateShippingInformation: function () {
              let validated = this._super();
              if (!validated) {
                  return validated;
              }
            //Perform your operation here and return the result true/false.
            return true;
          }
      });
  };
});

Add custom validation before Order Placement:
This article explains the­ process of adding custom validations before comple­ting an order during the checkout phase­. Specifically, it covers the validations that occur afte­r a shopper clicks on the "Place Orde­r" button.

Below are the steps to follow for adding a custom validation in payment step:
Step 1: create a new module
Step 2: Create a validator  
Create a <custom-validator>..js file for implementing the validation in    app/code/Vendor/Module/view/frontend/web/js/model directory.

define(
['mage/translate', 'Magento_Ui/js/model/messageList'],
function ($t, messageList) {
    'use strict';
    return {
        validate: function () {
            const isValid = false; //Put your validation logic here
            if (!isValid) {
                messageList.addErrorMessage({ message: $t('a possible failure message ...  ')    });
                                          }
            return isValid;
                  }
          }
}
);

Step 3: Add validator to your validator pool

To make your custom validator active, it needs to be added to the collection of "additional validators". This can be done by creating a <custom-validation>.js file in the app/code/Vendor/Module/view/frontend/web/js/view directory with the specified content. 

define(
  [
      'uiComponent',
      'Magento_Checkout/js/model/payment/additional-validators',
      'Vendor_Module/js/model/custom-validator'
  ],
  function (Component, additionalValidators, customValidator) {
      'use strict';
      additionalValidators.registerValidator(customValidator);
      return Component.extend({});
  }
);

Step 4: Create a validation in the checkout layout
In your custom module create a new file checkout_index_index.xml in app/code/Vendor/Module/view/frontend/layout directory 

    <argument name="jsLayout" xsi:type="array">
           <item name="components" xsi:type="array">
               <item name="checkout" xsi:type="array">
                   <item name="children" xsi:type="array">
                       <item name="steps" xsi:type="array">
                           <item name="children" xsi:type="array">
                               <item name="billing-step" xsi:type="array">
                                   <item name="children" xsi:type="array">
                                       <item name="payment" xsi:type="array">
                                           <item name="children" xsi:type="array">
                                               <item name="additional-payment-validators" xsi:type="array">
                                                   <item name="children" xsi:type="array">
                                                       <!-- Declare your validation. START -->
                                                       <item name="custom-validator" xsi:type="array">
                                                           <item name="component" xsi:type="string">%your_module_dir%/js/view/%custom-validation%</item>
                                                       </item>
                                                       <!-- Declare your validation. END -->
                                                   </item>
                                               </item>
                                           </item>
                                       </item>
                                   </item>
                               </item>
                           </item>
                       </item>
                   </item>
               </item>
           </item>
       </argument>
   </arguments>
</referenceBlock>

By following these steps, you can seamlessly add a custom validation in the payment step of your Magento checkout process. This enables you to tailor the payment validation to your specific requirements, providing a smoother and more user-friendly shopping experience for your customers.

It gives a guide on how to integrate validation into the shipping and payment stages of the checkout process. By utilizing the mixin `validateShippingInformation`, you can easily display customized messages based on specific conditions. This adaptable mixin empowers you to extend your validations beyond the shipping address and method to include custom fields. This flexibility allows you to create a seamless checkout process that aligns with your unique business requirements. By creating a custom validator in the payment step, you can ensure that specific checks are performed after a customer clicks the 'Place Order' button, thereby enhancing the security, accuracy, and overall checkout experience, all tailored to your unique business requirements.