How to create custom validation message in Magento 2

In this tutorial, we will guide you with a brief step by step process to set up a custom validation message in Magento 2. This article will help you add your own validation rule in Magento 2. In Magento 2, custom validation rules can be added with the use of Javascript mixin by creating it for "mage/validation" module. So lets see further how we can create a custom validation rule.

 

Please follow the below steps to create custom rule:

1. Create a javascript mixin file in our module path as given below path.

Path: <Vendor-name>/<Module-name>/view/frontend/web/js/custom-validation-rule-mixin.js

 

define(['jquery'], function($) {
  'use strict';

  return function() {
    $.validator.addMethod(
      'validate-ten-words',
      function(value, element) {
		//Perform your operation here and return the result true/false.
        return value.split(' ').length == 10;
      },
      $.mage.__('Your validation message.')
    )
  }
});

 

You can perform your logic for validation rule inside the addMethod function parameter. After performing the operation you can return true/false based on your condition.

2. Now you need to register the js file that we just created. First, you need to create a file requirejs-config.js inside below path.

Path: <Vendor-name>/<Module-name>/view/frontend/requirejs-config.js

var config = {
  config: {
    mixins: {
      'mage/validation': {
        'Vendor_Module/js/validation-mixin': true
      }
    }
  }
}

 

In the above code, you can replace the module name, vendor name, and file name.

3. We have successfully added a new custom method in jquery validation. Now let’s use this rule in the form. Now the only thing remaining is to apply this custom validation rule as "validate-ten-words" to inputs in the form we want to validate.

If you like this article, then share this with your Magneto friends and colleagues. Also, let us know your thoughts in the comments below. If something goes wrong while implementing the codes, then you can contact us at any time, and we will be happy to help you.