问题描述
<table id="myTable" cellspacing="40"></table>
每个项目最多可以包含50个字符,并且最多可以包含20个字符。
但是到目前为止很好...
我还必须验证数组中所有字符串的总长度不超过200个字符。
有可能纯粹在Joi吗?
解决方法
您似乎可以使用any.custom method and pass you custom validation logic。
基于该文档,我们首先需要创建一个函数来验证接受两个参数(“ value”和“ helpers”)的字符串数组。
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