4

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?

2

1 Answer 1

2

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.

1
  • Thanks for the help. I used the beforesave function in a backend model to validate my fields. But your solution seems
    – Thomas F
    Commented Feb 20, 2017 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.