Back to Top

How to add custom validation in store configuration field

Updated 28 April 2023

In this article, We will learn about how to add custom validation in store configuration field.

First off, We will create a module.

Step-1: Create requirejs-config.js in  app/code/Vendor/Validation/view/adminhtml

var config = {
    config: {
        mixins: {
            'mage/validation': {
                'Vendor_Validation/js/admin-config/validator-rules-mixin': true
            }
        }
    }
};

Step-2: Create validator-rules-mixin.js in  app/code/Vendor/Validation/view/adminhtml/web/js/admin-config

define([
    'jquery'
   ], function ($) {
       'use strict';
       return function (target) {
           $.validator.addMethod(
               'validate-server-protocol',
               function (value) {
                  if(value.includes('http') || value.includes('https')) {
                   return false;
                  } else {
                   return true;
                  }
               },
               $.mage.__('Please enter server name without protocol')
           );
           return target;
       };
   });

Step-3: Create system.xml in app/code/Vendor/Validation/etc/adminhtml and then add custom rule.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <group id="server_config" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
        <field id="host_name" translate="label comment" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0" >
            <label>Host</label>
            <comment>Ex: example.com</comment>
            <validate>required-entry validate-server-protocol</validate>
        </field>
        </group>
    </system>
</config>
storeConfig

Hope this will help you.

Thanks 🙂

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home