How to Add Validation in System Configuration in Magento 2
Magento 2 is a flexible platform that allows extending its functionality to satisfy the business requirements. Data validation is one such integral part that needs to be implemented for any type of E-commerce stores.
Not only frontend, but you may also want to add validation in system configuration in Magento 2. For example, validate the Email, check for the blank field, etc.
Using the below solution, you can validate any type of input fields in the Magento 2 stores configuration such as text field, date, drop-down, etc. as shown in the figure:
Method to Add Validation in System Configuration in Magento 2:
Place the below code at app/code/Meetanshi/HelloWorld/etc/adminhtml/system.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?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> <tab id="meetanshi" translate="label" sortOrder="50"> <label><![CDATA[<img src="https://meetanshi.com/media/logo.png" alt="Meetanshi" height="20" style="vertical-align:middle;"/>]]></label> </tab> <section id="helloworld" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1"> <class>separator-top</class> <label>Hello World</label> <tab>meetanshi</tab> <resource>Meetanshi_HelloWorld::config_helloworld</resource> <group id="general" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Configuration</label> <field id="enable" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Hello World</label> <source_model>Magento\Config\Model\Config\Source\Enabledisable</source_model> </field> </group> </section> </system> </config> |
That’s it.
Any doubts? Use the Comments section below to mention them. I’ll be happy to help.
Feel free to share the solution with fellow developers via social media to validate the input fields in Magento 2 system configuration.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Remove Image URL from sitemap.xml in Magento 2
How to Disable Cache for Block Using XML in Magento 2
Next