Question

I want to Add Validation of Comma Separated Values in Admin Configurations

I Know How to Add Custom Validation Using Js is just need the Regex (Regular Expression)

Was it helpful?

Solution

Magento2 manage the js validation using Css class.

Magento uses mage/validation, validation.js file and located in lib/web/mage directory of Magento2.

Then create requirejs-config.js at app/code/Vendor_Module/view/adminhtml/

add Below code:

var config = {
    config: {
        mixins: {
            'mage/validation': {
                'Vendor_Module/js/validation-mixin': true
            }
        }
    }
}

Add the Js validation class using the mixin at app/code/Vendor_Module/view/frontend/web/js/validation-mixin.js

Add below code:

define([
    'jquery'
], function ($) {
    "use strict";

    return function () {
        $.validator.addMethod(
            'validate-custom-regs-checker',
            function (value) {
        var regex;
        regex = (?i)\.(jpg|png|gif)$;
                if ($.mage.isEmpty(v) || !regex.test(v)) {
                    return false;
                }
                return true;
            },
            $.mage.__('Your validation error message')
        );
    }
});

image vakidation taken from https://stackoverflow.com/questions/169625/regex-to-check-if-valid-url-that-ends-in-jpg-png-or-gif

After that system.xml of add this new class using validate tag:

<field ...>
    ......
    <validate>validate-custom-regs-checker</validate>
</field>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top