本文介绍了Joi中any.when()的异常行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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没有显示任何错误?

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

推荐答案

不要忘记在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] ] } }

这篇关于Joi中any.when()的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:31