简体   繁体   English

Joi:如何验证数组中的所有项目具有相同的类型

[英]Joi: How to validate all items in array have the same type

My array can have multiple types:我的数组可以有多种类型:

[Joi.string(), Joi.number(), Joi.boolean(), Joi.array(), Joi.object()]

But I want to allow only one of them in the same time.但我想同时只允许其中一个。

I tried the following:我尝试了以下方法:

attributes: Joi.object().pattern(/\w+/, Joi.alternatives().try([Joi.array().items(Joi.string()), Joi.array().items(Joi.number()), Joi.array().items(Joi.boolean()), Joi.array().items(Joi.array()), Joi.array().items(Joi.object())]))

I'm using Joi 11.4.0.我正在使用 Joi 11.4.0。 I know it is an old version, but is there any way to perform such a validation?我知道这是一个旧版本,但是有什么方法可以执行这样的验证吗? Does it doable in another version?它在另一个版本中可行吗?

This works with version 11.4.0 but also the currently newest version 17.2.1这适用于版本11.4.0 ,但也适用于当前最新的版本17.2.1

const Joi = require('joi');

const schema = Joi.object({
  attributes: Joi.alternatives().try(
    Joi.array().items(Joi.string()),
    Joi.array().items(Joi.number()),
    Joi.array().items(Joi.boolean()),
    Joi.array().items(Joi.array()),
    Joi.array().items(Joi.object())
  )
  .required(),
})
.required();

const onlyStrings = {
  attributes: ['one', 'two', 'three']
};
console.log(schema.validate(onlyStrings).error);

const onlyNumbers = {
  attributes: [1, 2, 3],
};
console.log(schema.validate(onlyNumbers).error);

const onlyBooleans = {
  attributes: [false, true, false],
};
console.log(schema.validate(onlyBooleans).error);


const onlyArrays = {
  attributes: [[], [], []],
};
console.log(schema.validate(onlyArrays).error);

const onlyObjects = {
  attributes: [{}, {}, {}]
};
console.log(schema.validate(onlyObjects).error);

// fails
const stringAndNumbers = {
  attributes: ['one', 2, 'three']
};
console.log(schema.validate(stringAndNumbers).error);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM