How To

Magento 2: How to Add Custom Validation To System Configuration Field

Hello Magento Friends ?,

What’s going on? Welcome to Magento 2 technical solutions by MageComp. Today I am here demonstrating How to Add Custom Validation To System Configuration Field in Magento 2. Earlier I explained about How to Remove Apply Discount Code From Checkout Payment Page in Magento 2.

Beginning:

Validation is to restrict data entry on specific fields to avoid false entry. If the data does not match the validation rules it provides an error message telling the user to enter the correct data and do not allow the user to proceed further.

By default, Magento 2 provides some default built-in classes to validate system configuration fields. E.g. required field, validate non-negative numbers, a number greater than zero.

But what if you want to validate your system configuration field based on your requirement? E.g. validate the mobile number field with a minimum 10 digit number.

No worries, with the help of the below code you can Add Custom Validation in Magento 2 System Configuration Field.

So let us find out ?

Steps to Add Custom Validation To System Configuration Field in Magento 2:

Step 1: Update your system.xml file inside the following path: 

app\code\Vendor\Extension\etc\adminhtml\

Now, update the code with the below code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../Magento/Backend/etc/system_file.xsd">
    <system>
        <section id="customsection" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Custom Validation</label>
            <resource>Vendor_Extension::custom_config</resource>
            <group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <field id="mobilenumber" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Mobile Number</label>
                    <validate>required-entry validate-ten-degit</validate>
                </field>
            </group>
        </section>
    </system>
</config>

Note: Here “validate-ten-digit” is a Custom validation class.

Step 2: Next, create a requirejs-config.js file inside the below path:

app\code\Vendor\Extension\view\adminhtml\

And add this code:

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

Step 3: Next, create a validator-rules-mixin.js file inside the below path: 

app\code\Vendor\Extension\view\adminhtml\web\js\admin-config\

And add this code:

define([
 'jquery'
], function ($) {
    'use strict';
    return function (target) {
        $.validator.addMethod(
            'validate-ten-digit',
            function (value) {
                return !(value.length < 10);
            },
            $.mage.__('Please enter a 10 digit number.')
        );
        return target;
    };
});

Step 4: Finally run below commands.

php bin/magento setup:upgrade
 php bin/magento setup:static-content:deploy -f 
 php bin/magento cache:flush

That’s it.

Wrap Up:

I hope now you found the way to Add Custom Validation to System Configuration Field in Magento 2. If you find it hard to get, mention right away in the comment section below. I will be glad to fix up. Share the article with your friends and stay in touch with us.

Happy Coding ?

Click to rate this post!
[Total: 10 Average: 2.8]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

Mastering Tailwind CSS in Laravel: A Comprehensive Guide

Tailwind CSS has emerged as a powerful utility-first CSS framework, offering developers a unique approach…

2 days ago

React Native or Flutter in 2024

The mobile app development field has witnessed a rapid revolution over the past few years.…

4 days ago

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

7 days ago

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

1 week ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

1 week ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

1 week ago