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!
Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…
In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…
October was an exciting month for MageComp! From significant updates across our Magento 2 extension…
In modern web development, seamless navigation and state management are crucial for delivering a smooth…
Magento Open Source 2.4.8 beta version released on October 8, 2024. The latest release of…
Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…