使用 Joi

问题描述

我正在处理以下代码,我必须在其中使用 Joi 库执行一些验证。

验证解释如下:当 type 等于 ABC 并且在数组 arrayOfObjects 中有一个 objectInArray.id 等于允许值范围内的特定值(在这种情况下,UUID '012345ab-c678-910d-e111-f21g3h14i15j')以及当对象 anotherObjectInArray 不为 null 时,objectTovalidate 应该存在,并具有所需的属性 field1field2,否则 objectTovalidate 是可选的。

const data = {
    type: "ABC",arrayOfObjects: [
        {
            objectInArray: {
                id: '012345ab-c678-910d-e111-f21g3h14i15j',value: "test"
            },anotherObjectInArray: {
                some_field: "some_value"
            },otherData: "...",},{
            objectInArray: {
                id: '161718kl-m192-021n-o222-p32q4r25s26t',value: "test2"
            },otherData: "..."
        }
    ],objectTovalidate: {
        field1: "value",field2: true
    }
}

我尝试进行以下验证,但失败了。

objectTovalidate: Joi.when('type',{
    is: 'ABC',then: Joi.when('arrayOfObjects',{
        is: Joi.array().items(Joi.object({
            objectInArray: Joi.object({
                id: Joi.string().guid().required().valid('012345ab-c678-910d-e111-f21g3h14i15j','other_uuid')
            }).required()
        }).required()),{
            is: Joi.array().items(Joi.object({
                anotherObjectInArray: Joi.object().not(null)
            })),then: Joi.object({
                field1: Joi.string().required(),field2: Joi.boolean().strict().required()
            }).required(),otherwise: Joi.object().optional()
        }),otherwise: Joi.object().optional()
    }),otherwise: Joi.object().optional()
})

有人能指出我的代码有什么问题吗? :)

解决方法

你需要玩弄.when.has

此架构只是一个示例,您可能需要进行一些调整:

Joi.object({
  type: Joi.string(),arrayOfObjects:Joi.array(),objectToValidate: Joi.object()
}).when(Joi.object({ 
  type: Joi.valid('ABC'),arrayOfObjects: Joi.array().items().has(Joi.object({ 
      objectInArray: Joi.object({ id: Joi.valid('012345ab-c678-910d-e111-f21g3h14i15j'),value: Joi.valid() }),anotherObjectInArray: Joi.not(null)
    }).unknown()),}).unknown(),{
  then: Joi.object({
    objectToValidate: Joi.required()
  }),})

对于 .has,我们说必须至少存在一个符合这些条件的对象,这意味着这个例子将失败,因为至少有一个对象 objectInArray.id = 012345ab-c678-910d-e111-f21g3h14i15janotherObjectInArray 不为空,所以需要 objectToValidate

{
  type: "ABC",arrayOfObjects: [
    {
      objectInArray: {
        id: 'abcd',value: "test"
      },anotherObjectInArray: null
    },{
      objectInArray: {
        id: '012345ab-c678-910d-e111-f21g3h14i15j',anotherObjectInArray: { }
    }
  ]
}

错误如下:

验证错误:“objectToValidate”是必需的

并且这个对象会通过:

{
  type: "ABC",{
      objectInArray: {
        id: '12313',anotherObjectInArray: null
    }
  ]
}

因为我们没有必填字段,这意味着不需要 objectToValidate

而且,您不需要多次使用 Joi.optional(),这是默认设置。