[英]Joi array reducer?
我有一个 Joi 字符串数组:
const item = Joi.string().max(50)
const items = Joi.array().items(item).max(20)
每个单独的项目最多可以有 50 个字符,最多可以有 20 个项目。
到目前为止还不错,但是......
我还必须验证数组中所有字符串的总长度不超过 200 个字符。
是否有可能纯粹在 Joi 中?
看起来您可以使用any.custom 方法并向您传递自定义验证逻辑。
基于该文档,我们首先需要创建一个函数来验证接受两个参数的字符串数组,即“值”和“帮助器”对象。
const contentsLength = (value, helpers) => {
// do a map reduce to calculate the total length of strings in the array
const len = value.map((v) => v.length).reduce((acc, curr) => acc + curr, 0);
// make sure that then length doesn't exceed 20, if it does return an error using
// the message method on the helpers object
if (len > 200) {
return helpers.message(
"the contents of the array must not exceed 200 characters"
);
}
// otherwise return the array since it's valid
return value;
};
现在将其添加到您的items
架构中
const items = Joi.array().items(item).max(20).custom(contentsLength);
您可以使用有效和无效数组的示例查看此处的代码: https : //codesandbox.io/s/gallant-ptolemy-k7h5i?file=/ src/ index.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.