Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to add custom validations before order placement Magento 2

12-18-2024

How to add custom validations before order placement Magento 2

This article will help you add your own validation before placing an order.

This is the step where you add a new field and want to verify that field. For example, in the checkout, if a customer hasn’t selected input for a required field, the validation event will be triggered before he or she clicks on Place Order. This feature is helpful because it notifies customers of the missing information before completing the form.

Since we don’t add any new field, we will verify an existing field, the email field.

We will only allow orders with customers’ email from Google (Gmail) to go through.

Add custom validations before processing orders.

You should know how to create a basic Magento 2 module. All of customized files will be inside this module.

Let’s dive in the steps to add custom validations before order placement.

Step 1: Create the validator.

Create isGmail.js in Mageplaza/HelloWorld/view/frontend/web/js/model directory.
validate method is required

define(
    [
        'jquery',
        'mage/validation'
    ],
    function ($) {
        'use strict';

        return {

            /**
             * Validate checkout agreements
             *
             * @returns {Boolean}
             */
            validate: function () {
                var emailValidationResult = false;
                var email = $('form[data-role=email-with-possible-login]').val();
                if(~email.search("gmail.com")){ //should use Regular expression in real store.
                    emailValidationResult = true;
                }
                return emailValidationResult;
            }
        };
    }
);

Step 2: Add validator to the validators pool.

Create isGmail.js in Mageplaza/HelloWorld/view/frontend/web/js/view directory.

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

Step 3: Declare the validation in the checkout layout.

Add the following code to Mageplaza/HelloWorld/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="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="gmailValidation" xsi:type="array">
                                                                        <item name="component" xsi:type="string">Mageplaza_HelloWorld/js/view/isGmail</item>
                                                                    </item>
                                                                    <!-- Declare your validation. END -->
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </argument>
                </arguments>
        </referenceBlock>
    </body>
</page>

Step 4: Test the new validator.

Now time to flush cache and try to checkout with different emails. If you have any issue, feel free to leave a comment below, Mageplaza and Magento community are willing to help.

Wrap up

That’s all about adding custom validations before order placement in Magento 2. I hope you find the right tutorial for your work. If you have any questions, feel free to let me know. Thanks for reading!

x


    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services