Many times, store owners want to perform some custom validation before the order placement during checkout. These are the validations set when customers click Place Order button and some validations, restrictions or verifications need to be set prior to place the orders.
Here, we’ll talk about the method to add custom validations before order placement in Magento 2. For example, the store owner would want to verify the order before it is placed via OTP. The verification event is triggered before the click of the “Place Order” button. Likewise you can also set custom validation Message, This will allow you to display a custom message in the front end when the user enters an invalid or blank input. Similarly, like this example, you can run the below code to trigger any custom validation before the order is placed!
Method to Add Custom Validations Before Order Placement in Magento 2:
1. Create File in Path Vendor/Module/view/frontend/layout/checkout_index_index.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.root"> <arguments> <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="component" xsi:type="string">uiComponent</item> <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"> <item name="orderVerifyValidation" xsi:type="array"> <item name="component" xsi:type="string">Vendor_Module/js/view/validate</item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
2. Create File in Path Vendor/Module/view/frontend/web/js/view/validate.js
define( [ 'uiComponent', 'Magento_Checkout/js/model/payment/additional-validators', 'Vendor_Module/js/model/validate' ], function (Component, additionalValidators, orderCustomValidation) { 'use strict'; additionalValidators.registerValidator(orderCustomValidation); return Component.extend({}); } );
3. Create File in Path Vendor/Module/js/model/validate.js
define( [ 'jquery', 'Magento_Ui/js/modal/modal', 'mage/url', 'mage/validation' ], function ($, modal, url) { 'use strict'; return { validate: function () { var orderFlag = false; // Code for Order restrict here // return true if order success // return false if restrict order return orderFlag; } }; } );
Implement the above code and your task is done! You can also restrict order placement using plugin in Magento 2.
Happy Coding