【问题标题】:Unusual behaviour of any.when() in JoiJoi 中 any.when() 的异常行为
【发布时间】:2020-03-10 15:01:59
【问题描述】:
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

我也在schema_2 中出现错误
为什么schema_2 没有显示任何错误?

【问题讨论】:

  • 我相信 joi 不会验证架构中没有的任何字段。所以由于 b 没有被检查它不会失败。
  • 似乎when() 工作正常。不清楚你想做什么
  • schema_2 没有显示任何错误。我想在 a==5 使用 when 时看到错误。

标签: javascript json validation object joi


【解决方案1】:

不要忘记在schema_2 中添加b

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

这是结果。

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] ] } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多