JOI:允许数组中的空值

use*_*790 5 javascript node.js hapijs joi

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

Joi.array().items(Joi.string()).single().optional()
Run Code Online (Sandbox Code Playgroud)

我需要在有效载荷中允许空值。你能告诉我如何做到吗?

Cut*_*ert 9

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

Joi.array().items(Joi.string()).allow(null);
Run Code Online (Sandbox Code Playgroud)

如果要允许在数组内部使用null或空格字符串,请使用:

Joi.array().items(Joi.string().allow(null).allow(''));
Run Code Online (Sandbox Code Playgroud)

例:

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);
Run Code Online (Sandbox Code Playgroud)