Joi 数组减速器?
Joi array reducer?
我有一个 Joi 字符串数组:
const item = Joi.string().max(50)
const items = Joi.array().items(item).max(20)
每个项目最多 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
我有一个 Joi 字符串数组:
const item = Joi.string().max(50)
const items = Joi.array().items(item).max(20)
每个项目最多 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