【问题标题】:How to add a validation function to joi.any()?如何向 joi.any() 添加验证函数?
【发布时间】:2020-04-06 09:52:20
【问题描述】:

如何扩展joi.any() 以添加新规则?这样我就可以在任何现有类型上使用该规则,例如 joi.boolean()joi.string()

我知道如何使用扩展来扩展 joi 以添加新的自定义类型,但是这样做我无法将新类型与现有类型结合起来。

我希望能够做到joi.boolean().myrule()joi.string().myrule() 以及任何其他现有类型。我该怎么做?如果有什么不同,我会将它与最新版本的 joi 一起使用。

有什么办法可以通过joi.any.extend()any() 添加新规则而不是joi.extend()(添加新类型)。

【问题讨论】:

    标签: javascript node.js validation hapijs joi


    【解决方案1】:

    我看到了代码,但我认为这是不可能的(如果我错了,请纠正我)。您可以做的最接近的是: https://github.com/hapijs/joi/blob/master/test/extend.js#L95

    const custom = Joi.extend({
      type: /^s/, // <<< regex for type
      rules: {
        hello: {
          validate(value, helpers, args, options) {
            return 'hello';
          },
        },
      },
    });
    
    const string = custom.string().hello();
    expect(string.type).to.equal('string');
    expect(string.hello().validate('goodbye').value).to.equal('hello');
    
    const symbol = custom.symbol().hello();
    expect(symbol.type).to.equal('symbol');
    expect(symbol.hello().validate(Symbol('x')).value).to.equal('hello');
    

    因为在https://github.com/hapijs/joi/blob/master/lib/index.js#263:

    for (const type of joi._types) {
        if (extension.type.test(type)) {
            const item = Object.assign({}, extension);
            item.type = type;
            item.base = joi[type]();
            extended.push(item);
        }
    }
    

    Joi 正在使用 type 正则表达式检查它拥有的所有类型。

    也许您可以使用与您想要匹配的类型(或所有类型)匹配的正则表达式创建 customType。然后,例如,您可以使用custom.string(),而不是Joi.string()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-23
      • 2019-06-05
      • 2021-03-11
      • 2011-03-30
      • 1970-01-01
      • 2023-01-19
      • 2021-11-27
      • 2017-11-04
      相关资源
      最近更新 更多