Magento 2 Add Custom Validation Checkout

How To Add Custom Validation To Checkout in Magento 2

by admin

Hello everyone! Today, we’re excited to present another great article on Magento 2 add custom validation checkout. In this guide, we will walk you through the process of implementing custom validation rules for your checkout fields. Enhancing input validation not only improves user experience but also ensures data integrity, ultimately leading to a smoother checkout process for your customers. Let’s delve in!

Why Need to Add Magento 2 Custom Validation to Checkout

Adding custom validation to the checkout page is very helpful in many situations. If a customer hasn’t selected input for a required field on the checkout page, the validation event will be triggered before clicking Place Order.

Thus, this feature can prevent customers from missing any information field in the checkout.

For example, if you only offer free shipping in some specific city, you need to add a place field and validate its input to validate that the customer living in that city can get free shipping.

The good news is that you can enable that feature with the help of your coding knowledge as well as third-party extensions. So, in the Magento 2 tutorial for beginner developers below are the steps and codes you need to follow to add Magento 2 custom validation to the checkout.

Magento 2 Add Custom Validation Checkout: Implementing in 4 Steps

To add Magento 2 custom validation to the checkout, you need to follow 4 steps:

Step 1: Create a New JS File

First, you need to create a new JS file for adding a custom validation rule.

Let’s create a file with the name bsscommerceValidationRule.js

The file path will be app/code/<Vendor-name>/<Module-name>/view/frontend/web/js/bsscommerceValidationRule.js

Then add the below code to the file:

define([
    'jquery',
    'jquery/ui',
    'jquery/validate',
    'mage/translate'
    ], function($){
        'use strict';
        return function() {
            $.validator.addMethod(
                "bsscommercevalidationrule",
                function(value, element) {
                    //Perform your operation here and return the result true/false.
                    return true/false;
                },
                $.mage.__("Your validation message.")
            );
    }
});

Step 2: Register a New JS File

Next, you need to register the newly created js.

Create a filerequirejs-config.js file in app/code/<VendorName>/<ModuleName>/view/frontend/requirejs-config.js

Then add the below code inside the filerequirejs-config.js.

var config = {
   map: {
       "*": {
           bsscommerceMethod: "<VendorName_ModuleName>/js/bsscommerceValidationRule"
       }
   }
};

After that, add the below code to your phtml file.

<script type="text/x-magento-init">
   {
       "*": {
           "bsscommerceMethod": {}
       }
   }
</script>

You can pass arguments to js file inside x-magento-init, too.

<script type="text/x-magento-init">
   {
       "*": {
           "bsscommerceMethod": {
               "param": "paramvalue"
           }
       }
   }
</script>

You can also access these params inside the bsscommerceValidationRule.js file using the methods given below.

define([
   'jquery',
   'jquery/ui',
   'jquery/validate',
   'mage/translate'
], function($){
   'use strict';
   return function(param) {
       console.log(param);
       $.validator.addMethod(
           "bsscommercevalidationrule",
           function(value, element) {
               //Perform your operation here and return the result true/false.
               return true/false;
           },
           $.mage.__("Your validation message.")
       );
   }
});

Step 3: Apply the Rule to the Checkout Fields

You have successfully implemented the Magento 2 add custom validation rule using jQuery validation.

Now, let’s apply this rule in the checkout form. You need to include the new method in the data-validate attribute for the specific checkout field.

Here, bsscommercevalidationrule is the name of the custom validation rule we just created.

data-validate="{required:true, bsscommercevalidationrule:true}"

Step 4: Clear Cache and Check the Result

Run these commands and refresh the page.

php bin/magento cache:flush
php bin/magento setup:static-content:deploy

Finally, you can check your validation on the checkout page.

Also, don’t forget to save up to 50% of your checkout time with our Magento One Step Checkout!

For those interested in enhancing the checkout experience further, be sure to check out our blog on how to add a delivery date to the checkout page in Magento 2. This guide provides valuable insights into improving customer satisfaction by allowing them to select a preferred delivery date during checkout.

The Best Solution to Customize Your Checkout Page

Hereby, we want to introduce you to an amazing extension to further customize and optimize your Magento checkout page:

Magento 2 Checkout Custom Fields extension

Magento 2 Checkout Custom Field extension by BSS allows you to add many checkout fields as needed to collect customer information. Thanks to this, you can easily find customer insights and resolve any problems regarding your shopping experience.

This extension supports up to 7 input types for your custom checkout field, including date and time, text field, text area, yes/no, checkbox, radio button, and dropdown.

You can also segment customers to see custom fields. For example, If you have both B2B and B2C customers, you should personalize your checkout process for each customer group. Each group can see some different custom checkout fields.

You can add your custom checkout field in one of three checkout steps: Shipping Address, Shipping Method, or Review & Payments.

And with this extension, you can manage your checkout custom fields at ease.

Full list of features:

  • Input validation for store owners includes various types: Decimal Numbers, Integer Numbers, Emails, URLs, Letters, and Letters or Numbers
  • Add any number of Magento 2 custom fields to checkout
  • Use those fields as Magento 2 order attributes to improve management
  • Show custom fields  in the Order grid & on the Order Detail page
  • Add Magento 2 order custom attributes to transaction emails and documents
  • Get values of the created attributes via API

Conclusion: Magento 2 Add Custom Validation Checkout

In this article, we have shown you a full guide on how to add Magento 2 custom validation to checkout.

We hope this blog is helpful and good luck to you!

BSS Commerce is one of the leading Magento eCommerce extension providers and Magento development company in the world. With experienced and certified Magento developers, we commit to bringing high-quality products and services to optimize your business effectively. Furthermore, we offer FREE Installation – FREE 1-year Support and FREE Lifetime Update for every Magento extension.

CONTACT NOW to let us know your problems. We are willing to support you every time.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.