Skip to content

Commit ed25e95

Browse files
authored
strictUnknown should honor local explicit .unknown(false) (#3037)
1 parent 5b96852 commit ed25e95

File tree

2 files changed

+69
-2
lines changed

2 files changed

+69
-2
lines changed

lib/types/keys.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ module.exports = Any.extend({
3131

3232
flags: {
3333

34-
unknown: { default: false }
34+
unknown: { default: undefined }
3535
},
3636

3737
terms: {
@@ -972,7 +972,7 @@ internals.unknown = function (schema, value, unprocessed, errors, state, prefs)
972972
return;
973973
}
974974

975-
if (prefs.stripUnknown && !schema._flags.unknown ||
975+
if (prefs.stripUnknown && typeof schema._flags.unknown === 'undefined' ||
976976
prefs.skipFunctions) {
977977

978978
const stripUnknown = prefs.stripUnknown ? (prefs.stripUnknown === true ? true : !!prefs.stripUnknown.objects) : false;

test/index.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,73 @@ describe('Joi', () => {
635635
Helper.validate(schema, { stripUnknown: { arrays: false, objects: true }, allowUnknown: true }, [[obj, true, { a: 1, b: 'a' }]]);
636636
});
637637

638+
it('validates enforces local behavior of unknown(true) when stripUnknown is set', () => {
639+
640+
const schema = Joi.object({
641+
a: Joi.number().min(0).max(3),
642+
loosyObject: Joi.object({
643+
b1: Joi.string()
644+
}).unknown(true), // allows extra keys
645+
anotherLoosyObject: Joi.object({
646+
c1: Joi.string()
647+
}).unknown() // also allows extra keys
648+
});
649+
650+
const obj = {
651+
a: 1,
652+
loosyObject: {
653+
b1: 'c1',
654+
b2: 'c2'
655+
},
656+
anotherLoosyObject: {
657+
c1: 'c1',
658+
c2: 'c2'
659+
}
660+
};
661+
662+
Helper.validate(schema, { stripUnknown: true }, [[obj, true, {
663+
a: 1,
664+
loosyObject: {
665+
b1: 'c1',
666+
b2: 'c2'
667+
},
668+
anotherLoosyObject: {
669+
c1: 'c1',
670+
c2: 'c2'
671+
}
672+
}]]);
673+
});
674+
675+
it('validates enforces local behavior of unknown(false) when stripUnknown is set', () => {
676+
677+
const schema = Joi.object({
678+
a: Joi.number().min(0).max(3),
679+
strictObject: Joi.object({
680+
b1: Joi.string()
681+
}).unknown(false) // it shouldn't allow extra keys
682+
});
683+
684+
const obj = {
685+
a: 1,
686+
strictObject: {
687+
b1: 'b1',
688+
b2: 'b2'
689+
}
690+
};
691+
692+
Helper.validate(schema, { stripUnknown: true }, [[obj, false, {
693+
message: '"strictObject.b2" is not allowed',
694+
path: ['strictObject', 'b2'],
695+
type: 'object.unknown',
696+
context: {
697+
child: 'b2',
698+
label: 'strictObject.b2',
699+
key: 'b2',
700+
value: 'b2'
701+
}
702+
}]]);
703+
});
704+
638705
it('validates dependencies when stripUnknown is set', () => {
639706

640707
const schema = Joi.object({

0 commit comments

Comments
 (0)