Question

Is it possible to create a custom validation for fields in configuration? (Stores > Settings > configuration)

I created a system.xml file but the default values for the validate tag are not enough for my needs and I would like to create my own rules.

I found an other question about this but it doesn't say how and where I should put/declare the validation method.

Is this possible or is the only solution to create a backend model with a beforeSave function?

Was it helpful?

Solution

As far as I know, if we want to add more custom validations. We should validate with beforeSave(). For example, take a look the cookie validation: vendor/magento/module-cookie/Model/Config/Backend/Lifetime.php.

We can add more Js validation for the user interface input.

A Sample to add Js validation for system xml:

In your module, create file the layout - adminhtml_system_config_edit.xml

enter image description here

app/code/Vendor/Module/view/adminhtml/layout/adminhtml_system_config_edit.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="js">
            <block class="Magento\Backend\Block\Template" 
                   template="Module_Vendor::system/config/custom_js.phtml"/>
        </referenceContainer>
    </body>
</page>

Remember to add your custom validation in the template.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top