0

for our customer I've to create a custom validation for a field in the shipping-address-fieldset. For that I've created a custom module in /app/code. The js requirement works but the validation doesn't appear. Here is what I've got (anonymised):

/app/code/[Vendor]/[Module]/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'mage/validation': {
                '[Vendor]_[Module]/js/test-mixin': true
            }
        }
    }
}

/app/code/[Vendor]/[Module]/view/frontend/web/js/test-mixin.js

define([
    'jquery',
    'jquery/ui',
    'jquery/validate',
    'mage/translate'
], function($) {
    'use strict';

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

and I've tried to add the validator to the company field in checkout_index_index.xml

<item name="company" xsi:type="array">
    <item name="validation" xsi:type="array">
        <item name="required-entry" xsi:type="boolean">true</item>
        <item name="validate-five-words" xsi:type="boolean">true</item>
    </item>
</item>

The required-entry validation and others like validate-street are working correctly. May be it's the wrong mixin hook or I miss something else.

2
  • You want to create compony field validation??? Jan 30 '21 at 6:29
  • min and max 5 character enter in compny field right ??? Jan 30 '21 at 6:30
1

app/code/[Vendor]/[Module]/view/frontend

requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Ui/js/lib/validation/validator': {
                'Namespace_Modulename/js/test-mixin': true
            }
        }
    }
}

app/code/[Vendor]/[Module]/view/frontend/web/js

test-mixin.js

define(
    ['jquery'],
   function($) {
  "use strict";
    return function(validator) {
        validator.addRule(
            'validate-five-words',
                function(value, element) { 
                    return value.split(' ').length == 5;
                },
            $.mage.__('If any Error then put here the Message')
        );
        return validator;
    }
});

I Hope This Helps You.

1
  • 1
    Almost right. The inner function needs a second argument "element", e.g. function(value, element){ return value.split(' ').length == 5;}
    – Pete
    Jan 31 '21 at 20:58

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.