6

I'm going crazy here trying to add a custom validation rule to Magento 2. It's impossible to find any useful information about it.

The things I have are as follow:

1) requirejs-config.js file with the following content:

var config = {
map: {
    '*': {
        experius_postcodenl_validation_rule:'Experius_Postcode/js/validation/postcodenl-validation-rule',
        experius_postcode:'Experius_Postcode/js/widget/postcode'
    }
}};

2) Seperate javascript file:

define([
"jquery",
"experius_postcode", // Custom knockout view model
'jquery/validate',
"validation",
"mage/translate"
], function($,experiusPostcode) {
"use strict";

    $.validator.addMethod(
        'validate-postcode-housenumber-combination',
        function (value) { 
            // My validation
        },
        $.mage.__('No address could be found.')
    );
});

This should be enough to add a custom validation rule to the global jquery validator object not?

I Double checked all the file paths. The requirejs-condig.js gets loaded (checked in my browsers network tab). No 404 errors on sources whatsoever.

Am I missing something?

ps: don't mind the validation rule itself. Its still a dummy rule

19

One thing you could try is to add a JavaScript mixin:

In requirejs-config.js do:

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

and Vendor_Module/view/frontend/web/js/validation-mixin.js:

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

    return function () {
        $.validator.addMethod(
            'validate-minimum-age',
            function (value) {
                // Some custom validation stuff here
                return true or false;
            },
            $.mage.__('Your validation error message')
        );
    }
});

This way your validation rule will extend the original JS validation object and will be available everywhere.

  • Would these validations also be available on the checkout? – Jurģis Toms Liepiņš Feb 5 '18 at 11:35
  • @JurģisTomsLiepiņš on my side it's not working. Magento use a different javascript called validation/rules.js but using same logic for overwriting is not working – Sylvain Rayé Feb 15 '18 at 1:47
  • A fully working example for the checkout here magento.stackexchange.com/questions/209042/… – Sylvain Rayé Feb 15 '18 at 10:42
  • @Giel Berkers : I have tried sample code it's working fine but in production mode i'm enabling the minify js that time "validation-mixin.min.js is not created in pub/static/frontend/theme But in the url it's included like validation-mixin.min.js please check and let me know – Ramki Aug 1 '18 at 13:06
  • This doesn't work – cjohansson Sep 20 at 10:50

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.