Magento 2 Create Custom Validation Rules

In Magento 2, we can add the custom validation rules by creating a Javascript mixin for the mage/validation module and calling the $.validator.addMethod function with the custom validation rule parameters as described below:

Syntax To Create New Validation Rule:

$.validator.addMethod(
  'custom-rule-name',
  function(value, element) {
    // You need to return true or false after validation rule check
  },
  $.mage.__('Add error message here to display if validation fails')
)

Following is the code snippet which adds a simple new validation rule to the mixin to validate if an input field has only four words.

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

var config = {
  config: {
    mixins: {
      'mage/validation': {
        'Vendor_Module/js/custom-validation-mixin': true
      }
    }
  }
}
Path: app/code/Vendor/Module/view/frontend/web/js/custom-validation-mixin.js

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

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

Hope this helps !

Leave a Reply