Magento 2 Tutorial How To Add Custom Validation To Checkout

by admin

Hello everyone, today we will show you another great Magento 2 article on how to add 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 they click on 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 the customer living in that city and can get freeship.

The good news is that you can enable that feature with the help of your coding knowledge. So below are the steps and codes you need to follow to add Magento 2 custom validation to the checkout.

How To Add Magento 2 Custom Validation In Checkout

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 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 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 added the new custom method in jquery validation. 

Now let’s use this rule in the checkout form.

You need to add a new method in data-validate attribute for the specific checkout field.

Here bsscommercevalidationrule is the name of our newly created validation rule.

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.

EXPLORE NOW: 10+ Best Magento 2 One Step Checkout Extension Free & Paid!

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 Field by BSS

magento-2-checkout-custom-field

 

Magento 2 Checkout Custom Field 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.

And 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:

  • 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

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 extensions providers and web development services 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.

NEW: We have launched Trello’s Product Roadmap to keep you updated on our latest product versions. Share your feedback and suggestions for Magento solutions to help us improve your experience here. With our Product Roadmap, you can also request updates or compatibility for your desired modules or suggest a new one to enhance your website.

>>
Explore NOW! 

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.