Extend Magento 2 rules.js without overwriting the core js file?

Viewed 1111

Is it possible to overwrite the Magento_Ui/js/lib/validation/rules.js file without map - ing the file as in the below example?

var config = {
    "map": {
        "*" : {
            'Magento_Ui/js/lib/validation/rules' : 'Test_Custom/js/validation/rules'
        }
    }
};

Is there a more elegant way to add a form validation that can be used as well on the checkout steps?

Thanks

1 Answers

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

var config = {
config: {
    mixins: {
        'Magento_Ui/js/lib/validation/rules': {
            'Vendor_Module/js/lib/validation/rules': true
           }
         }
      }
 };

Create rules.js in Vendor/Module/view/base/web/js/lib/validation

define([
'jquery',
'underscore',
'moment',
'mage/translate'
], function ($, _, moment) {
'use strict';

return function (validator) {
    var validators = {
        'validate-number-custom': [
            function (value) {
                console.log("You logic here");
                return /^[a-zA-Z ]*$/i.test(value);
            },
            $.mage.__('Please enter a valid number in this field.')
        ]
    };

    validators = _.mapObject(validators, function (data) {
        return {
            handler: data[0],
            message: data[1]
        };
    });

    return $.extend(validator, validators);
  };
});
Related