Hello Magento Friends,
Welcome back to Magento “How To” blog category. Today we will discuss Magento 2: How to Add Custom Validation Rule in knockout Validation Rules. In case you haven’t taken a glance at our previously published blog, How to Add Customer Name in CMS Page/Block in Magento 2.
Contents
At the time of development, there is plenty of data received from customers. It is required to apply validation to these data. And developers have requirements to add a custom Validation on the front side while submitting any data to the server. So let us look at the steps, Magento 2: How to Add Custom Validation Rule in knockout Validation Rules.
Step 1: Create requirejs-config.js at the below path
app\code\Vendor\Extension\view\frontend\requirejs-config.js
And the below code
var config = { config: { mixins: { 'Magento_Ui/js/lib/validation/validator': { 'Vendor_Extension/js/custom-validation': true }, } } };
Using Mixins, we override the Validator file to our file.
Step 2: Now, create a custom-validation.js file at the below path
app\code\Vendor\Extension\view\frontend\web\js\custom-validation.js
And add the code as follows
define(['jquery'], function($) { "use strict"; return function(validator) { validator.addRule( 'validate-name', function(value) { /* Custom validation logic */}, $.mage.__('If any Error then put here the Message') ); return validator; } });
We have to override the AddRule function for adding our custom rules. So from now if you put ‘validate-name’ anywhere in the frontend input field it will validate the field as per custom logic.
Therefore, all are now able to Add Custom Validation Rule in knockout Validation Rules in Magento 2. If you come across any trouble, mention it in the comment section below without any hesitation. Spread the solution further with your Magento colleagues. Stay updated with us for the latest solution.
Happy Coding!
In the world of business, understanding financial metrics is crucial for making informed decisions and…
Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…
In this era, businesses are always on the lookout for ways to engage with their…
Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…
E-commerce has transformed the way consumers shop for products and services and interact with businesses.…
The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…