Magento, Magento 2

How to Add Custom Validation Rule in Magento 2

How to Add Custom Validation Rule in Magento 2

In this tutorial, Today I will explain to how to add custom validation rule in Magento 2.In Magento , There are many default validation available. It will be useful to check all validation when submit form. But, now if you want to create custom validation rule based on your requirement then, you need to follow the below steps :

You may also like this :

1) First of all, Let’s assume that you have created simple module. Now, create requirejs-config.js file at app/code/RH/Helloworld/view/frontend/ to create mixin file of validation rule :

var config = {
    config: {
        mixins: {
            'mage/validation': {
                'RH_Helloworld/js/custom-validation': true
            },
        }
    }
};

2) After that, Create custom-validation.js file app/code/RH/Helloworld/view/frontend/js/ and paste the below code :

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

  return function() {
    $.validator.addMethod(
      'validate-min-ten',
      function(value, element) {
        return value.split(' ').length >= 10;
      },
      $.mage.__('Please enter 10 character or greater than 10')
    )
  }
});

This rule is for enter minimum 10 character in textbox. You need to use validate-min-ten validation rule in your textbox element. In your input field, it will be like this :

data-validate="{required:true, 'validate-min-ten':true}"

That’s it !!!

I hope this blog is easy to understand about how to add custom validation rule in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing !!

Tagged ,