基于数组对象属性值的joi验证

编程入门 行业动态 更新时间:2024-10-10 12:19:40

基于<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组对象属性值的joi验证"/>

基于数组对象属性值的joi验证

我有一组要验证的数据:

{
   "createUser": {
     "isCustomer": true or false,
     "data": {
       "product": [ // sometimes array of object with id : 3
        {
         "id":46,
         "sumInsured":"4562000",
        },
        {
         "id":45,
         "sumInsured":"8532000",
        },
        ]
   }
}

这些是我们需要验证的以下方案:

1) validate array of objects
2) isCustomer is mandatory when id is 45
3) isCustomer not allowed when id is 3

首先完成:

Joi.object({
  data: Joi.array()
        .items({
          id: Joi.number().valid(3,45,46)
            .required(),
          sumInsured: Joi.string()
            .required()
        }),
})

我对相同内容进行了很多搜索,但仍然找不到相同的解决方案。

任何帮助将不胜感激。

提前感谢。

回答如下:

2)id为45时isCustomer是必需的

您需要Joi.ref("dotnotation.of.key").when.required.forbidden才能验证子/父值

要点2

const dataSchema = Joi.object({
  product: Joi.array().items(
    Joi.object({
      id: Joi.number().valid(3, 45, 46),
    })
  ),
});

const dataIsMandatory = Joi.object({
  product: Joi.array().items(
    Joi.object({
      id: Joi.number().valid(45),
    })
  ),
});

const schema2 = Joi.object({
  createUser: Joi.object({
    isCustomer: Joi.any().when("data", {
      is: dataIsMandatory,
      then: Joi.bool().required(),
    }),

    data: dataSchema,
  }),
});

测试用例

const test2_ok = {
  createUser: {
    isCustomer: true,
    data: {
      product: [
        {
          id: 45,
        },
      ],
    },
  },
};

const test2_requires_customer = {
  createUser: {
    data: {
      product: [
        {
          id: 45,
        },
      ],
    },
  },
};

const test2_does_not_require_customer = {
  createUser: {
    data: {
      product: [
        {
          id: 46,
        },
      ],
    },
  },
};


const test2_does_not_require_customer_should_error = {
  isCustomer: true,
  createUser: {
    data: {
      product: [
        {
          id: 46,
        },
      ],
    },
  },
};

schema2.validate(test2_ok); //? ok if 45
schema2.validate(test2_requires_customer); //? error if 45 - require isCustomer 
schema2.validate(test2_does_not_require_customer); //? ok if 46
schema2.validate(test2_does_not_require_customer_should_error); //? error if 46 - if isCustomer

更多推荐

基于数组对象属性值的joi验证

本文发布于:2024-05-07 11:16:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   属性   对象   joi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!