HOW TO CREATE CUSTOM FORM VALIDATION ON MAGENTO 2

There are many predefined js validation rules available in magneto 2 and for applying those validation you just need to add CSS class. For example:-

  1. min-words
  2. range-words
  3. alphanumeric
  4. letters-only
  5. integer
  6. zip-range
  7. max-words
  8. Integer
  9. no-whitespace
  10. validate-url

And so on. The list is long.

But sometimes, you need to add your own custom validation rule that is not available in default Magento. In that case, you need to define your own validation script. In this article, we will add our own validation rules. So, let’s begin.

Note: You can create module.xml and registration.php by yourself as we have discussed in our previous articles. Please follow our other modules for this. For example, this article has the registration part: https://www.www.bizspice.com/blog/post/write-custom-shipping-plugin-in-magento/

Step 1: Create A New Js File.

You need to create a new js file in your module for adding custom validation rule. Let’s create a file

app/code/<Vendor-name>/<Module-name>/view/frontend/web/js/customValidationRule.js

define([
 'jquery',
 'jquery/ui',
 'jquery/validate',
 'mage/translate'
 ],
 function($){
     'use strict';
  return function() {
     $.validator.addMethod( "customvalidation", function (value, element) {
     return !/<script\b[^>]*>([\s\S]*?)<\/script>/.test(value);
  },
  $.mage.__('SCRIPT tags are not allowed.')
  ); 
 } 
}); 

This is the basic structure of the js file. Here we have added a new validation rule and called it customvalidation. We will use this in our front-end form wherever we need our custom validation. We have used the jquery validator’s addMethod for registering a new method.

Perform your logic for validation rule inside the addMethod function parameter, as we did it for checking Script Tags. After performing the operation, you can return true/false based on your condition. (we did both in the same line). And finally, add your custom validation message, which will be displayed whenever the validation fails.

Step 2: Register A New Js File.

As you have created your own JS file, now is the time to register this newly created file. For this you have to create requirejs-config.js file inside app/code/<VendorName>/<ModuleName>/view/frontend/

var config = {
               map: {
                      "*": {
                              customValidationMethod: "<VendorName_ModuleName>/js/customValidationRule"
                           }
                     }
              }; 

We have defined customValidationMethod method, which we are going to add to our form.

Step 3: Apply Newly Created Rule To The Form Fields.

Now we have added a new custom method in jQuery validation, and it is time to implement the rule in our form. For this, you need to add this new method(customValidationMethod) in the phtml file or form.

<form class="form contact"
action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); >?>"
id="contact-form"
method="post"
data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
data-mage-init='{
"validation":{},
"customValidationMethod":{}
}'>

You can also add this code given below in your phtml file instead of adding in the form tag.

<script type="text/x-magento-init">
     {
       "*": {
                "customValidationMethod": {}
            } 
     }
</script> 

Here “*” means all forms in the current phtml file.

And finally, the field on which we are applying validation. We will use the method inside data-validate attribute for a specific field inside the form.

Here customvalidation is the name of our newly created validation rule.

So, let’s put this validation in the form.

<form class="form contact" ………………>
<!-- other form content -->
    <div class="field name required">
        <label class="label" for="customfield">
            <span>Custom Field</span>
        </label>
      <div class="control">
         <input name="customfield" id="customfield" title="custom field" value="" class="input-text" type="text" data-validate="{required:true, customvalidation :true}" />
      </div>
   </div>
<!-- other form content --> 
</form> 

In the above field, we have bound our Custom validation rule inside the data-validate, where we also define that the field is required and our custom validation. Now, if we try to enter any script tag in the field, it will throw the validation message that “SCRIPT tags are not allowed.”