Skip to content

Commit

Permalink
strictUnknown should honor local explicit .unknown(false)
Browse files Browse the repository at this point in the history
  • Loading branch information
afharo authored and Marsup committed Jun 19, 2024
1 parent 0066a4e commit add6597
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/types/keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ module.exports = Any.extend({

flags: {

unknown: { default: false }
unknown: { default: undefined }
},

terms: {
Expand Down Expand Up @@ -974,7 +974,7 @@ internals.unknown = function (schema, value, unprocessed, errors, state, prefs)
return;
}

if (prefs.stripUnknown && !schema._flags.unknown ||
if (prefs.stripUnknown && typeof schema._flags.unknown === 'undefined' ||
prefs.skipFunctions) {

const stripUnknown = prefs.stripUnknown ? (prefs.stripUnknown === true ? true : !!prefs.stripUnknown.objects) : false;
Expand Down
67 changes: 67 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,73 @@ describe('Joi', () => {
Helper.validate(schema, { stripUnknown: { arrays: false, objects: true }, allowUnknown: true }, [[obj, true, { a: 1, b: 'a' }]]);
});

it('validates enforces local behavior of unknown(true) when stripUnknown is set', () => {

const schema = Joi.object({
a: Joi.number().min(0).max(3),
loosyObject: Joi.object({
b1: Joi.string()
}).unknown(true), // allows extra keys
anotherLoosyObject: Joi.object({
c1: Joi.string()
}).unknown() // also allows extra keys
});

const obj = {
a: 1,
loosyObject: {
b1: 'c1',
b2: 'c2'
},
anotherLoosyObject: {
c1: 'c1',
c2: 'c2'
}
};

Helper.validate(schema, { stripUnknown: true }, [[obj, true, {
a: 1,
loosyObject: {
b1: 'c1',
b2: 'c2'
},
anotherLoosyObject: {
c1: 'c1',
c2: 'c2'
}
}]]);
});

it('validates enforces local behavior of unknown(false) when stripUnknown is set', () => {

const schema = Joi.object({
a: Joi.number().min(0).max(3),
strictObject: Joi.object({
b1: Joi.string()
}).unknown(false) // it shouldn't allow extra keys
});

const obj = {
a: 1,
strictObject: {
b1: 'b1',
b2: 'b2'
}
};

Helper.validate(schema, { stripUnknown: true }, [[obj, false, {
message: '"strictObject.b2" is not allowed',
path: ['strictObject', 'b2'],
type: 'object.unknown',
context: {
child: 'b2',
label: 'strictObject.b2',
key: 'b2',
value: 'b2'
}
}]]);
});

it('validates dependencies when stripUnknown is set', () => {

const schema = Joi.object({
Expand Down

0 comments on commit add6597

Please sign in to comment.