node.js 如何使用 Joi 验证对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37744483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:17:59  来源:igfitidea点击:

How to validate array of objects using Joi?

node.jsvalidationexpressjoi

提问by zakir

I am getting an array of objects to backend, where each object contains a service name. The structure looks like below

我正在向后端获取一组对象,其中每个对象都包含一个服务名称。结构如下

[{"serviceName":"service1"},
{"serviceName":"service2"},..]

when I get the array at backend, I want to validate that every object in the array has serviceName property.

当我在后端获取数组时,我想验证数组中的每个对象是否都具有 serviceName 属性。

I had written the following code, but even though I pass valid array, I am getting validation error.

我编写了以下代码,但即使我传递了有效数组,我也收到了验证错误。

var Joi = require('joi');
var service = Joi.object().keys({
  serviceName: Joi.string().required()
});

var services = Joi.array().ordered(service);

var test = Joi.validate([{serviceName:'service1'},{serviceName:'service2'}],services)

For the above code, I am always getting the validation error with message

对于上面的代码,我总是收到带有消息的验证错误

"value" at position 1 fails because array must contain at most 1 items

回答by zakir

replacing orderedwith itemswill work.

物品替换订购物品将起作用。

let Joi = require('joi')
let service = Joi.object().keys({
  serviceName: Joi.string().required(),
})

let services = Joi.array().items(service)

let test = Joi.validate(
  [{ serviceName: 'service1' }, { serviceName: 'service2' }],
  services,
)

For reference click here

参考点击这里

回答by sediq khan

A basic/ clearer example is as follows. To validate a JSON request like this:

一个基本/更清晰的例子如下。要验证这样的 JSON 请求:

   {
    "data": [
            {
        "keyword":"test",
        "country_code":"de",
        "language":"de",
        "depth":1
            }
        ]
    }

Here is the Joi validation:

这是 Joi 验证:

 seoPostBody: {
    body: {
      data: Joi.array()
        .items({
          keyword: Joi.string()
            .required(),
          country_code: Joi.string()
            .required(),
          language: Joi.string()
            .required(),
          depth: Joi.number()
            .required(),
        }),
    },
  };

This is what I am doing in NodeJs, might need some slight changes for other platforms

这是我在 NodeJs 中所做的,对于其他平台可能需要一些细微的更改

回答by Him Hah

Just want to make it more clear. I'm currently using "@hapi/joi:16.1.7".

只是想让它更清楚。我目前正在使用“@hapi/joi:16.1.7”。

Let's say you want your schema to validate this array of objects.

假设您希望架构验证这个对象数组。

const example = [
   {
      "foo": "bar",
      "num": 1,
      "is_active": true,
   }
];

Then schema's rules should be:

那么架构的规则应该是:

var validator = require('@hapi/joi');

const rules = validator.array().items(
    validator.object(
        foo: validator.string().required(),
        num: validator.number().required(),
        is_active: validator.boolean().required(),
    ),
);

const { error } = rules.validate(example);

回答by PrashantAjani

For Joi you can use below which is working fine for me, this will validate that array must have at-least on object with key serviceName-

对于 Joi,您可以在下面使用它,这对我来说很好用,这将验证该数组必须至少具有关键 serviceName- 的对象

const Joi = require('joi');
const itemsArray = Joi.array().items(
            Joi.object({
                serviceName: Joi.string().required(),
            })
        ).min(1).required();

        const itemSchema = Joi.array().items(itemsArray).when('checkout_type', {
            is: 'guest',
            then: Joi.array().required(),
        }).required();

let schema = Joi.object().keys({
        items: Joi.alternatives().try(itemsArray, itemSchema).required(),
    });