Magento 2 How To Create Custom Validation Rule/Message

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.

We have to follow these steps to create custom rule:

  1. Create a javascript mixin file in our module path as given below path:
Path: Vendor/ModuleName/view/frontend/web/js/custom-validation-rule-mixin.js 

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

  return function() {
    $.validator.addMethod(
      'validate-ten-words',
      function(value, element) {
        return value.split(' ').length == 10;
      },
      $.mage.__('Please enter exactly ten words')
    )
  }
});

2. Next we have to add this validation rule to require js config file of module.

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

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

3. We are done with creation of new validation rule. Now only thing remaining is to apply this custom validation rule as “validate-ten-words” to inputs in form we want to validate.

Hope this helps you guys!

Leave a Reply