diff --git a/lib/extend.js b/lib/extend.js index a5498717f..4bb489ed9 100755 --- a/lib/extend.js +++ b/lib/extend.js @@ -34,27 +34,28 @@ exports.root = function (root, extensions) { root.assert(extension, Schemas.extension); - const base = (extension.base || root.any()).clone(); // Cloning because we're going to override messages afterwards + const base = extension.base || root.any(); const ctor = base.constructor; - const type = class extends ctor { // eslint-disable-line no-loop-func + const type = class extends ctor { // eslint-disable-line no-loop-func constructor() { super(); if (extension.base) { - Object.assign(this, base); + Object.assign(this, extension.base); } this._type = extension.name; + + if (extension.messages) { + const existing = base._preferences && Hoek.clone(base._preferences.messages); + this._preferences = Object.assign({}, this._preferences); + this._preferences.messages = Messages.compile(extension.messages, existing); + } } }; - if (extension.messages) { - const existing = type.prototype._messages || base._preferences && base._preferences.messages; - type.prototype._messages = Messages.compile(extension.messages, existing); - } - if (extension.coerce) { type.prototype._coerce = function (value, state, prefs) { diff --git a/lib/validator.js b/lib/validator.js index cbfb1bb93..2c52b67c1 100755 --- a/lib/validator.js +++ b/lib/validator.js @@ -358,7 +358,7 @@ internals.prefs = function (schema, prefs) { return schema._preferences[Common.symbols.prefs]; } - prefs = Common.preferences(schema._messages ? Common.preferences({ messages: schema._messages }, prefs) : prefs, schema._preferences); + prefs = Common.preferences(prefs, schema._preferences); if (isDefaultOptions) { schema._preferences[Common.symbols.prefs] = prefs; } @@ -366,10 +366,6 @@ internals.prefs = function (schema, prefs) { return prefs; } - if (schema._messages) { - return Common.preferences({ messages: schema._messages }, prefs); - } - return prefs; }; diff --git a/test/extend.js b/test/extend.js index 4c182e8f1..dff3a5d96 100755 --- a/test/extend.js +++ b/test/extend.js @@ -534,7 +534,7 @@ describe('extension', () => { expect(schema.validate(3)).to.contain({ error: null, value: 6 }); }); - it('does not override a predefined messages', () => { + it('overrides base messages', () => { const base = Joi.any().prefs({ messages: { @@ -566,7 +566,7 @@ describe('extension', () => { const schema = customJoi.myType().foo(); const result = schema.validate({}); expect(result.error).to.be.an.instanceof(Error); - expect(result.error.toString()).to.equal('ValidationError: "value" original'); + expect(result.error.toString()).to.equal('ValidationError: "value" modified'); }); it('does not change predefined options', () => {