【问题标题】:Joi array reducer?Joi数组减速器?
【发布时间】:2020-10-01 23:14:44
【问题描述】:

我有一个 Joi 字符串数组:

const item = Joi.string().max(50)
const items = Joi.array().items(item).max(20)

每个单独的项目最多可以有 50 个字符,最多有 20 个项目。

到目前为止一切都很好,但是......

我还必须验证数组中所有字符串的总长度不超过 200 个字符。

是否可以纯粹在 Joi 中实现?

【问题讨论】:

  • 你使用的是什么版本的 joi?
  • 最新(17.2.1)

标签: javascript node.js validation joi


【解决方案1】:

看来您可以使用any.custom method and pass you custom validation logic

根据该文档,我们首先需要创建一个函数来验证字符串数组,该数组接受两个参数,即“值”和“助手”对象。

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

【讨论】:

  • 出色——我错过了文档林中的那棵树。感谢您为我指明方向,这开启了各种可能性。
猜你喜欢
  • 2016-04-16
  • 2017-02-26
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 2017-08-21
相关资源
最近更新 更多