【问题标题】:JOI alternatives try - need one to be requiredJOI 替代品尝试 - 需要一个
【发布时间】:2020-04-03 16:20:50
【问题描述】:

我正在尝试使用 JOI 和 express-validation 验证查询字符串。

我需要查询参数 ?query[primaryOrgId]=5d2f2c836aeed10026ccba11 是单个字符串或字符串数​​组,这是必需的。

以下架构正在按预期验证primaryOrgId(当它存在时),但并未验证它是否是必需的:

 index: {
    body: {},
    query: {
      query: {
        primaryOrgId: Joi.alternatives().try(
          Joi.array().items(Joi.string().regex(mongoId)),
          Joi.string().regex(mongoId),
        ).required()
      },
    },
    options: {
      allowUnknownQuery: false,
      allowUnknownBody: false,
    },
  },

我也试过了:

 index: {
    body: {},
    query: {
      query: {
        primaryOrgId: Joi.alternatives().try(
          Joi.array().items(Joi.string().regex(mongoId).required()),
          Joi.string().regex(mongoId).required(),
        )
      },
    },
    options: {
      allowUnknownQuery: false,
      allowUnknownBody: false,
    },
  },
}

如何确保查询字符串中存在primaryOrgId?

【问题讨论】:

    标签: node.js joi


    【解决方案1】:

    我不能 100% 确定您的要求,但这里有一个 Joi ("@hapi/joi": "^17.1.1") 架构,有一些更改:

    const schema = Joi.alternatives().try(
      Joi.array().min(1).items(Joi.string().trim()), // length have to be at least 1
      Joi.string().trim()
    ).required(); // required added
    
    // String
    console.log(schema.validate(undefined)); // error: [Error [ValidationError]: "value" is required]
    console.log(schema.validate('')); // error: [Error [ValidationError]: "value" is not allowed to be empty]
    console.log(schema.validate(' ')); // error: [Error [ValidationError]: "value" is not allowed to be empty]
    console.log(schema.validate('foo')); // value: 'foo'
    
    // Array
    console.log(schema.validate([])); // error: [Error [ValidationError]: "value" must contain at least 1 items]
    console.log(schema.validate([' '])); // error: [Error [ValidationError]: "[0]" is not allowed to be empty]
    console.log(schema.validate(['foo'])); // value: [ 'foo' ]
    console.log(schema.validate(['foo', 'bar'])); //  value: [ 'foo', 'bar' ]
    

    让我知道这是否适合您。否则我会更新我的答案。

    【讨论】:

    • 谢谢!我已经接受了答案。不幸的是,这对我不起作用,我使用的是依赖于 Joi 的 express-validation,而不是 @hapi/joi,所以我认为 Join 版本已经过时。我要改成 evanshortiss/express-joi-validation,除非你有更好的建议?
    • 啊,好吧。有道理。不幸的是,我没有更好的建议,因为我使用 hapi 而不是 express。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多