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?

asked Feb 1, 2017 at 15:47
2
  • To your question on how/where put the code for magento.stackexchange.com/questions/139023/… : You have to create a custom js file and then add js code in it. Then include that file in your code. Commented Feb 1, 2017 at 16:03
  • See my updated answer. Commented Feb 19, 2017 at 10:57

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.

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.