Unusual behaviour of any.when() in Joi

北城以北 提交于 2019-12-11 16:56:03

问题


const Joi = require('@hapi/joi')

var schema_1 = Joi.object({
    a: Joi.number().integer(),
    b: Joi.number().integer()
}).when(Joi.object({
    'a': Joi.number().valid(5),
    'b': Joi.number().valid(10),
}), {then: Joi.any().forbidden()})

var schema_2 = Joi.object({
    a: Joi.number().integer(),
    b: Joi.number().integer()
}).when(Joi.object({
    'a': Joi.number().valid(5),
}), {then: Joi.any().forbidden()})

var object = {
    a: 5,
    b: 10
}

schema_1.validate(object) // this throws ValidationError
schema_2.validate(object) // this does not throw any error

I was expeting error in schema_2 also
Why schema_2 is not showing any error?


回答1:


Do not forget to add b as well in the schema_2.

const Joi = require('@hapi/joi')

var schema_1 = Joi.object({
    a: Joi.number().integer(),
    b: Joi.number().integer()
}).when(Joi.object({
    'a': Joi.number().valid(5),
    'b': Joi.number().valid(10),
}), {then: Joi.any().forbidden()})

var schema_2 = Joi.object({
    a: Joi.number().integer(),
    b: Joi.number().integer()
}).when(Joi.object({
    'a': Joi.number().valid(5),
    'b': Joi.any(),
}), {then: Joi.any().forbidden()})

var object = {
    a: 5,
    b: 10
}

schema_1.validate(object) // this throws ValidationError
schema_2.validate(object) // this does not throw any error

Here is the result.

const x = schema_1.validate(object) // this throws ValidationError
const y = schema_2.validate(object) // this does not throw any error

console.log(x)
console.log(y)
{ value: { a: 5, b: 10 },
  error:
   { ValidationError: "value" is not allowed _original: { a: 5, b: 10 }, details: [ [Object] ] } }
{ value: { a: 5, b: 10 },
  error:
   { ValidationError: "value" is not allowed _original: { a: 5, b: 10 }, details: [ [Object] ] } }


来源:https://stackoverflow.com/questions/58860414/unusual-behaviour-of-any-when-in-joi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!