>Magento 2: Add Validation in Configuration

Magento 2: Add Validation in Configuration

In this article we will cover how to add validation in System Configuration for Magento 2.

Validation in Configuration

Here is a simple example after creating a file system.xml.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="bss" translate="label" sortOrder="300">
            <label><![CDATA[Bss Commerce]]></label>
        </tab>
        <section id="bss_admin_config_validate" translate="label" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>Admin Config Validate</label>
            <tab>bss</tab>
            <resource>Bss_AdminConfigValidate:config</resource>
            <group id="bss_product_image_by_customer_general" translate="label" type="text" sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General Configuration</label>
                <field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Enabled</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    <comment><![CDATA[Version 1.0.0]]></comment>
                </field>
                <field id="speed_slide" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Slideshow Speed</label>
                </field>
            </group>
        </textsection>
    </system>
</config>

Go to Stores -> Settings -> Configuration -> Bss Commerce -> Admin Config Validate, we get a page admin config with fields already:

In which:

  • Enable: Select “Yes” to enable the module, “No” to disable the module.
  • Slideshow Speed: Fill in numbers.

Furthermore, Magento 2 provides the available classes to help you ask Users to fill in required types through the class defined in the tag with the structure: [name-class-validate].

Please note that Magento 2 supports many validated types in a tag by calling classes separating by “a space”:

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="bss" translate="label" sortOrder="300">
            <label><![CDATA[Bss Commerce]]></label>
        </tab>
        <section id="bss_admin_config_validate" translate="label" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>Admin Config Validate</label>
            <tab>bss</tab>
            <resource>Bss_AdminConfigValidate:config</resource>
            <group id="bss_product_image_by_customer_general" translate="label" type="text" sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General Configuration</label>
                <field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Enabled</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    <comment><![CDATspeedA[Version 1.0.0]]></comment>
                </field>
                <field id="speed_slide" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Slideshow Speed</label>
                    <validate>validate-not-negative-number</validate>
                </field>
            </group>
        </section>
    </system>
</config>

After adding the validate tag: <validate> validate-not-negative-number </ validate>, a message “Please enter number 0 or greater than in this field” is shown as below image.

Otherwise, Magento also supports you validate server side through by:

<backend_model>[Name_Company]\[Name_module]\Model\Config\Backend\[Name_Class]

In tag backend_model, we declare class which is inherited from parent class \Magento\Framework\App\Config\Value. The parent class supports the functions such as beforeSave, afterSave, getData.

Here is a simple example of function “saveBefore”.

public function beforeSave()
    {
        if ($this->getValue() == '') {
            throw new \Magento\Framework\Exception\ValidatorException(__($label . ' is required.'));
        } else if (!is_numeric($this->getValue())) {
            throw new \Magento\Framework\Exception\ValidatorException(__($label . ' is not a number.'));
        }
        $this->setValue(intval($this->getValue()));
        parent::beforeSave();
    }

Some important validation classes

validate-no-html-tags HTML tags are not allowed.
validate-select Please select an option.
validate-no-empty Empty Value
validate-alphanum-with-spaces Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field.
validate-data Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter.
validate-street Please use only letters (a-z or A-Z), numbers (0-9), spaces and “#” in this field.
validate-phoneStrict Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.
validate-phoneLax Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.
validate-fax Please enter a valid fax number (Ex: 123-456-7890).
validate-email Please enter a valid email address (Ex: johndoe@domain.com).
validate-emailSender Please enter a valid email address (Ex: johndoe@domain.com).
validate-password Please enter 6 or more characters. Leading and trailing spaces will be ignored.
validate-admin-password Please enter 7 or more characters, using both numeric and alphabetic.
validate-url Please enter a valid URL. Protocol is required (http://, https:// or ftp://).
validate-clean-url Please enter a valid URL. For example http://www.example.com or www.example.com.
validate-xml-identifier Please enter a valid XML-identifier (Ex: something_1, block5, id-4).
validate-ssn Please enter a valid social security number (Ex: 123-45-6789).
validate-zip-us Please enter a valid zip code (Ex: 90602 or 90602-1234).
validate-date-au Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.
validate-currency-dollar Please enter a valid $ amount. For example $100.00.

If you have any problems or need our professional service, please email us support@bsscommerce.com. You can also find the right solution in our best-in-class https://bsscommerce.com/magento-2-extensions.html

< Previous Post
Next Post >