TransWikia.com

Magento 2 : Problem Adding Validation Form With Mixin

Magento Asked by Jurģis Toms Liepiņš on January 4, 2022

I am trying to add a custom validation form with mixin.

I have created simple module Mageplaza_Helloworld.

In appcodeMageplazaHelloWorldviewfrontendwebjsrequirejs-config.js:

<script type="text/javascript">
var config = {
    config: {
        mixins: {
            'mage/validation': {
                'Mageplaza_HelloWorld/js/validation-mixin': true
            }
        }
    }
}
</script> 

And in: appcodeMageplazaHelloWorldviewfrontendwebjsvalidation-mixin.js:

<script type="text/javascript">
define([
    'jquery'
], function ($) {
    "use strict";

    return function () {
        $.validator.addMethod(
            'validate-jurgis',
            function (value) {
                $.mage.__('Your validation error message');
                return false;
            },

        );
    }
});
</strict>

Im returing false just to see if it works at all (which it doesnt)

And in vendormagentomodule-checkoutviewfrontendlayoutcheckout_index_index.xml I assign it like:

<item name="telephone" xsi:type="array">
    <item name="config" xsi:type="array">
        <item name="tooltip" xsi:type="array">
            <item name="description" xsi:type="string" translate="true">For delivery questions.</item>
        </item>
    </item>
    <!-- add a validation code at here -->
    <item name="validation" xsi:type="array">
        <item name="validate-jurgis" xsi:type="string">true</item>
    </item>
    <!-- end of validation -->
</item>

(If I replace validate-jurgis with an existing form, it works)

But it doesnt work. I get no errors and am able to proceed…

Attempt nr. 3

appcodeMageplazaHelloWorldviewbasewebjsrequirejs-config.js

<script type="text/javascript">
var config = {
    config: {
        mixins: {
            'Magento_Ui/view/base/web/js/lib/validation/rules': {
                'Mageplaza_HelloWorld/js/validation-mixin': true
            }
        }
    }
}
</script> 

appcodeMageplazaHelloWorldviewbasewebjsvalidation-mixin.js

<script type="text/javascript">
define([
    'mage/translate'
], function ($t) {
    'use strict';

    return function (rules) {
        rules['validate-jurgis'] = {
            handler: function () {
                return false;
            },
            message: $t('My message')
        };

        return rules;
    };
});
</script>

vendormagentomodule-checkoutviewfrontendlayoutcheckout_index_index.xml

<item name="validation" xsi:type="array">
<item name="validate-jurgis" xsi:type="string">true</item>
</item>

2 Answers

@Logan great info, there is a more supported way to add to the UI rules.

Add the mixin:

'Magento_Ui/js/lib/validation/validator': {
            'js/my-ui-validation': true
        }

Then add the rule definition:

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

    return function (validator) {

        validator.addRule(
            'my-custom-phone-number-rule',
            function (value, params, additionalParams) {
                return $.mage.isEmptyNoTrim(value) || value.match(/^[0-9 .-]+$/);
            },
            $.mage.__("Please enter a valid phone number.")
        );

        return validator;
    };
});

Answered by Joel Davey on January 4, 2022

Hi @Jurģis Toms Liepiņš - your answer helped me a lot!

Multiple Validation Methods

It appears there are two JavaScript validation implementations:

1. mage/validation.js

The mage/validation file is referenced by mage/validation/validation, which is mapped with RequireJS to validation:

'validation': 'mage/validation/validation'

Inchoo has an article on how to use this.

2. Magento_Ui/js/lib/validation/rules.js

The Magento_Ui/js/lib/validation/rules.js file is referenced in Magento_Ui/js/form/element/abstract and Magento_Ui/js/form/element/file-uploader and seems to be used to validate UI form elements.

Example using this validation in XML layout:

<item name="example-input-element" xsi:type="array">
    <item name="component" xsi:type="string">Magento_Ui/js/form/element/abstract</item>
    <item name="config" xsi:type="array">
        <item name="customScope" xsi:type="string">shippingAddress</item>
        <item name="template" xsi:type="string">ui/form/field</item>
        <item name=elementTmpl" xsi:type="string">ui/form/element/input</item>
    </item>
    <item name="validation" xsi:type="array">
        <item name="required-entry" xsi:type="boolean">true</item>
        <item name="max_text_length" xsi:type="number">255</item>
        <item name="validate-address-not-pobox" xsi:type="boolean">true</item>
    </item>
</item>



Usage + Examples

Here is the necessary code to add custom validation rules to the two implementations:

Example RequireJS Configuration

/**
 * File:
 * requirejs-config.js
 */

var config = {
    config: {
        mixins: {
            'mage/validation': {
                'js/my-validation': true
            },
            'Magento_Ui/js/lib/validation/rules': {
                'js/my-ui-validation': true
            }
        }
    }
};


Example mage/validation Mixin

/**
 * File:
 * js/my-validation.js
 */

define(['jquery'], function ($) {
    'use strict';
    
    return function() {
        // PO Box addresses
        $.validator.addMethod(
            'validate-address-not-pobox',
            function (v) {
                return !/p(s|.){0,2}?o(s|.){0,2}?.*box|post(s|.){0,2}?office/i.test(v);
            },
            $.mage.__('Address cannot be a PO Box address.')
        );
    }
});


Example Magento_Ui/js/lib/validation/rules Mixin

Note: Joel Davey shows another great way to add validation methods for UI elements

/**
 * File:
 * js/my-ui-validation.js
 */

define(['mage/translate'], function($t) {
    'use strict';
    
    return function(rules) {
        rules['validate-address-not-pobox'] = {
            handler: function (v) {
                return !/p(s|.){0,2}?o(s|.){0,2}?.*box|post(s|.){0,2}?office/i.test(v);
            },
            message: $t('Address cannot be a PO Box address.')
        };
        return rules;
    };
});

Answered by Logan on January 4, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP