0

Custom adminhtml validation rules from Magento 2 docs on purely installed Magento 2.4.3 and Magento 2.4.2 doesn't work.

Vendor/Module/view/frontend/requirejs-config.js

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

Vendor/Module/view/frontend/web/js/validation-mixin.js

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

  return function() {
    $.validator.addMethod(
      'validate-five-words',
      function(value, element) {
        return value.split(' ').length == 5;
      },
      $.mage.__('Please enter exactly five words')
    )
  }
});

Vendor/Module/etc/adminhtml/system.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="vendor" class="vendor-tab" translate="label">
            <label>Vendor</label>
        </tab>

        <section id="vendor" translate="label" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Label</label>
            <tab>Vendor</tab>
            <resource>Vendor_Module::config</resource>

            <group id="module" showInDefault="1" showInWebsite="1" showInStore="1" translate="label">
                <label>Module</label>

                <field id="field" showInDefault="1" showInWebsite="1" showInStore="1" translate="label" canRestore="1" type="text">
                    <label>Field</label>
                    <validate>validation-mixin</validate>
                </field>
            </group>
        </section>
    </system>
</config>

Vendor/Module/etc/config.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <vendor>
            <module>
                <field>1 2 3 4 5</field>
            </module>
        </vendor>
    </default>
</config>

When saving, nothing happens to me.

When adding standard Magento rules <validate>validate-number</validate>, they work.

What am I doing wrong? or maybe something is missing?

1

You need to add "requirejs-config.js" and "validation-mixin.js" in adminhtml instead of frontend as below path

Vendor/Module/view/adminhtml/requirejs-config.js

and need to put js file on below path

Vendor/Module/view/adminhtml/web/js/validation-mixin.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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