Add Custom Validation Rule in Magento 2

Apr 10th, 2018 5 min to read

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!

FAQs

How to validate phone number on checkout page in magento2?


To validate phone number on the checkout page in Magento 2, you can use the Customer Attributes feature. Navigate to Stores>Attributes>Customer and click on “Add New Attribute”. Add the default label and specify the value in Input Type. Set the Input Validation field to numeric only. Set the text length and “Use in Customer Segment” option to Yes. Navigate to the Storefront Properties section and set the Show on Storefront option to Yes and select the checkout page form to display the column in the checkout page. Lastly, click on the save button.

What are custom validation rules?


Custom validation rules are an additional set of validations you can add to check key data entries. These rules are applied during the customer process, restricting the entries according to the set rules. For example, you can limit the number of words in a field or accept phone numbers with a specific country code. If the entries don’t meet the rules, you can also display a validation error message.

How to add validation in Magento 2 form?


To add validation in Magento 2 form, use the following methods:
1. Create a new JavaScript file with the custom validation rule.
2. Register the new file by creating a filerequirejs-config.js
3. Add the new rule in the input fields by using the rule name as an attribute or a class name. 
4. Apply the rule to the desired forms.
5. Test the form for proper implementation of the new rule.

How to add validation in system configuration in Magento 2?


To add validation in system configuration in Magento 2, you need to modify the system.xml file by adding the validate tag. Then, pass the required validation classes in the added tag. You can check it by navigating to Stores>Settings>Configuration and find the newly added validation fields.

Speak your Mind

Post a Comment

Got a question? Have a feedback? Please feel free to leave your ideas, opinions, and questions in the comments section of our post! ❤️

* This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Thank you for your feedback

Comments (2)

  1. Much appreciated

    Reply
  2. Hello,
    Can i add custom validation on post-code field using your method.
    I want to execute Google Zip Code validation on post-code field to ensure given address is valid or not.
    Please advise.

    Reply

Grow your online business like 2,174 subscribers

    * This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
    envelope

    Thank You!

    We are reviewing your submission, and will be in touch shortly.