Skip to content

Unexpected interaction between Joi.object().unknown() and stripUnknown #983

@cdhowie

Description

@cdhowie

Context

  • node version: 4.5.0
  • joi version: 9.0.4
  • environment (node, browser): node

What are you trying to achieve or the steps to reproduce ?

There's a bit of ambiguity between the object().unknown() schema and the { stripUnknown: { objects: true } } validation options. I would expect the stripUnknown option to leave unknown keys alone if the schema declares that it allows unknown keys, but this is not the case; it removes unknown keys regardless of whether the schema permits them.

This puts me in a rather difficult position of having to know which schemas permit unknown keys and which do not, so that I can supply the correct stripUnknown option during validation. My requirements:

  • If an object schema does not allow unknown keys, they are removed without causing an error.
  • If an object schema allows unknown keys, they are ignored.

This particular use case seems to be missing from Joi. Perhaps we could add { stripUnknown: { objects: 'unallowed' } } to cover this? I'm more than happy to submit a PR to add this but want to make sure that this approach would be accepted before I start working on it.

'use strict';

const Joi = require('joi');

let schema = Joi.object().keys({
    a: Joi.string().required()
});

let obj = {
    a: "foo",
    b: "bar"
};

console.log(schema.validate(obj));

console.log(schema.validate(obj, { stripUnknown: { objects: true } }));

console.log(schema.unknown().validate(obj));

console.log(schema.unknown().validate(obj, { stripUnknown: { objects: true } }));

Which result you had ?

{ error:
   { [ValidationError: "b" is not allowed]
     isJoi: true,
     name: 'ValidationError',
     details: [ [Object] ],
     _object: { a: 'foo', b: 'bar' },
     annotate: [Function] },
  value: { a: 'foo', b: 'bar' } }
{ error: null, value: { a: 'foo' } }
{ error: null, value: { a: 'foo', b: 'bar' } }
{ error: null, value: { a: 'foo' } }

What did you expect ?

{ error:
   { [ValidationError: "b" is not allowed]
     isJoi: true,
     name: 'ValidationError',
     details: [ [Object] ],
     _object: { a: 'foo', b: 'bar' },
     annotate: [Function] },
  value: { a: 'foo', b: 'bar' } }
{ error: null, value: { a: 'foo' } }
{ error: null, value: { a: 'foo', b: 'bar' } }
{ error: null, value: { a: 'foo', b: 'bar' } }

Metadata

Metadata

Assignees

Labels

bugBug or defect

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions