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.
Introduction:
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.
Steps to Add Custom Validation Rule in knockout Validation Rules in Magento 2:
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.
Conclusion:
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!