Add Custom Validation Rule in Magento 2

By: Saurabh Parekh, Apr 10th, 2018 # Magento 2 # Frontend # How to

Add Custom Validation Rule in Magento 2 - Aureate Labs

This article will help you add your own validation rule in Magento 2. Below are the steps which will help you to add a custom validation rule inside your module.

Step 1: Create a new js file
Step 2: Register a new js file
Step 3: Apply the newly created rule to the form fields
Step 4: Clear cache and check the form

Step 1: Create a new js file

You need to create a new js file in your module for adding a custom validation rule. Let’s create a file with the name aureatelabsValidationRule.js. File path should be app/code/<Vendor-name>/<Module-name>/view/frontend/web/js/aureatelabsValidationRule.js.
Inside this file you need to add the below code snippet:

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

Above is the basic structure of the js file. You need to include require js file for adding a new method.
Here we have added a new validation rule aureatelabsvalidationrule. You can give any name for your validation rule. We have use jquery validator's addMethod for registering a new method.
You can perform your logic for validation rule inside addMethod function parameter. After performing operation you can return true/false based on your condition.
Now the last parameter of addMethod is a validation message. Here you can add your custom validation message which will be displayed whenever the validation fails.

Step 2: Register a new js file

Now you need to register newly created js. First, you need to create a filerequirejs-config.js inside app/code/<VendorName>/<ModuleName>/view/frontend/requirejs-config.js.
Add the code given below inside the filerequirejs-config.js.

var config = {
   map: {
       "*": {
           aureatelabsMethod: "<VendorName_ModuleName>/js/aureatelabsValidationRule"
       }
   }
};

In the above code, you can replace your module and vendor name. You can replace your js file name with aureatelabsValidationRule.
After that, you need to add the code given below in your phtml file.

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

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

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

You can also access these params inside aureatelabsValidationRule.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(
           "aureatelabsvalidationrule",
           function(value, element) {
               //Perform your operation here and return the result true/false.
               return true/false;
           },
           $.mage.__("Your validation message.")
       );
   }
});

Step 3: Apply the newly created rule to the form fields

We have successfully added a new custom method in jquery validation. Now let’s use this rule in the form.
You need to add a new method inside data-validate attribute for the specific field inside the form.
Here aureatelabsvalidationrule is the name of our newly created validation rule.
data-validate="{required:true, 'aureatelabsvalidationrule':true}"
We have successfully bound the newly created method with the form.

Step 4: Clear cache and check the form

Execute these commands and refresh the page.
php bin/magento cache:flush
php bin/magento setup:static-content:deploy
You can check your validation now. Fill up the form and click on submit button to check your validation.

Happy coding!