Magento 2: How to Add Custom Validations Before Order Placement?

Magento 2: How to Add Custom Validations Before Order Placement?

The topmost reason merchants prefer Magento over other platforms is the level of customisation it offers. With Magento, there is no limit to what you can customise according to your unique requirements. One example of this customisation is the ability to add a custom validation before the user places an order.

What Do We Mean by Add Custom Validations in Magento 2?

It is easy to get confused by this term. So, let’s understand with the help of an example. Suppose your store is based in the US but caters to audiences in Canada. Of course, shipping overseas is costly and various taxes must be factored in. To offset this cost and ensure that you still make a profit, you introduce a minimum order quantity.

For instance, instead of letting Canadian users order only one item at time, you make them buy 5 orders at least. A custom validation will ensure that unless there are 5 items in the cart, the order cannot be processed. In other words, a custom validation places checks and conditions that must be met before an action can be completed.

Setting Up Magento 2 Add Custom Validation Rule

In this article, we will see how to add custom validations before order placement in Magento 2. For example, you don’t offer shipping in a specific State and want to validate the shopper has not selected that State. You can also add new field and validate its input. The verification event is triggered before a shopper clicks the “Place Order” button. The following steps will allow you to implement any custom validation before order placement.

Step 1: Create the Validator At the Module Level

Create a .js file in your custom module directory. This is to implement the validator. In this case, the custom module directory is FME/Hello and we create a validate.js file in FME/Hello/view/frontend/web/js/model directory. Following is a sample of the validator. You can code according to your custom validation.

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

Step 2: Add Validator to the Validators Pool

Create validate.js in FME/Hello/view/frontend/web/js/view directory.

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

Step 3: Declare the Validation in the Checkout Layout

Add the following code to FME/Hello/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>

Now, that you have implemented the above code. Flush the Cache and validate the implemented code.

Conclusion

A custom validation ensures that all orders meet the defined criteria before being processed. This ensures financial stability and helps overcome administrative headaches. If you’re facing any issue regarding how to add custom validations in Magento 2, then feel free to contact our support team for an instant fix.

Related Articles: