Back to Top

Add custom validation in the input field in the system.xml

Updated 19 June 2024

Hello Friends!

In this blog, we will learn how we can add custom validation in a field by creating custom validation class from jquery in system.xml.

To add custom validation in a store configuration field, please follow the below steps:

1. Create requirejs-config.js file inside the app/code/Vendor/CustomModule/view/adminhtml/ directory.

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

2. Create validator-rules-mixin.js file inside the app/code/Vendor/CustomModule/view/adminhtml/web/js/store-config/ directory.

define([
 'jquery'
], function ($) {
    'use strict';
    return function (target) {
        $.validator.addMethod(
            'validate-sixteen-digit',
            function (value) {
                console.log(value);
                return !(value.length < 16);
            },
            $.mage.__('Please Enter 16 Digit Number.')
        );
        return target;
    };
});

3. Create system.xml file inside the app/code/Vendor/CustomModule/etc/adminhtml/ directory. And add the validation class ‘validate-sixteen-digit’ in ‘Aadhaar Number’ field.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Config/etc/system_file.xsd">
    <system>
        <tab id="vendorname" translate="label" sortOrder="10">
            <label>VendorName</label>
        </tab>
        <section id="custommodule" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Custom Module Configuration</label>
            <tab>vendorname</tab>
            <resource>Vendor_CustomModule::config_blogs</resource>
            <group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <field id="aadhaarnumber" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Aadhaar Number</label>
                    <validate>required-entry <em>validate-sixteen-digit</em></validate>
                </field>
            </group>
        </section>
    </system>
</config>

4. See the result in the below image.

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

Hope this will be helpful. Thanks 🙂

Previous Blog: Override Product Tier Prices in Magento 2

Next Blog: Validate system.xml fields data when saving the configuration

. . .

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