Magento – Magento 2 add custom validation rule

magento-2.1magento2requirejsvalidation

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

Best Answer

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.

Related Topic