Add multiple Validation in System Configuration – Magento2

You can also pass multiple validation classes in validate tag by just adding space between classes.

<field id="base_url" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0">
    <label>Service Base URL</label>
    <validate>required-entry validate-url</validate>
    <comment>Enter your comment here</comment>
</field>

I read few places that we can use multiple validate tags as well but it doesn’t work for me.

<field id="base_url" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0">
    <label>Service Base URL</label>
    <validate>required-entry</validate>
    <validate>validate-url</validate>
    <comment>Enter your comment here</comment>
</field>
Validate Empty Field
Validate URL

Call validation from Javascript.

<script>
    require([
        'jquery',
        'prototype',
        'mage/validation',
        'mage/translate'
    ], function ($, prototype, validate, $t) {
        function validateUrl() {
            $('#YOUR_INPUT_FIELD_ID').validation();
            if(!$('#YOUR_INPUT_FIELD_ID').validation('isValid')){
                return false;
            }
        }
        $('#validate_base_url').click(function () {
            validateUrl();
        });
    });
</script>

The javascript code above will validate URL input field when user click on Validate Base URL button if you want to validate before saving the value using Save Config button.

Thank you so much for reading hope this is helpful.

Leave a Reply

Your email address will not be published.