JOI:允许数组中的空值

JOI :allow null values in array

我正在尝试为 POST 请求中的数组添加验证

Joi.array().items(Joi.string()).single().optional()

我需要在负载中允许空值。你能告诉我怎么做吗?

如果要允许数组为空,请使用:

Joi.array().items(Joi.string()).allow(null);

如果您想在数组中使用空字符串或空白字符串,请使用:

Joi.array().items(Joi.string().allow(null).allow(''));

示例:

const Joi = require('joi');

var schema = Joi.array().items(Joi.string()).allow(null);

var arr = null;

var result = Joi.validate(arr, schema); 

console.log(result); // {error: null}

arr = ['1', '2'];

result = Joi.validate(arr, schema);

console.log(result); // {error: null}


var insideSchema = Joi.array().items(Joi.string().allow(null).allow(''));

var insideResult = Joi.validate(['1', null, '2'], insideSchema);

console.log(insideResult);

我知道我发布的不是你要找的, 但因为我 运行 遇到了类似的问题。

所以我的问题是:我不想在我的对象中允许空数组

我的解决方案:

// if you have array of numbers

key: joi.array().items(joi.number().required()).strict().required()

// if you have array of strings

key: joi.array().items(joi.string().required()).strict().required()

最简短的答案是:

name: Joi.string().allow(null)