Magento2 – Custom Field Validation in system.xml

magento2system.xmlvalidation

I'm developing the magento2 plugin(I'm kinda new in magento2), and I ran into a problem with validation the field in system.xml. I've been searching for a long time and did not find the answer. I added a new field but I need to validate this field using the regex. I saw that there is a some default validation but I need custom one, is there any way to add a new validation rule to validator?

Best Answer

Basically, you need to register your custom validation method and then use it for your field in system.xml file.

Define your validation method:

jQuery.validator.addMethod(
    "validate-custom", 
    function (v) {
        return jQuery.mage.isEmptyNoTrim(v) || /^[1-4]+$/.test(v);
     },
    'Please use digits only (1-4) in this field.'
);

And use it for your field in system.xml:

<validate>validate-number validate-zero-or-greater validate-custom</validate>

Search for "validator.addMethod" in the Magento 2 core code, there are a bunch of examples there showing more complex use cases.