[英]How to add a validation function to joi.any()?
如何扩展joi.any()
以向其添加新规则? 这样我就可以在任何现有类型上使用该规则,例如joi.boolean()
或joi.string()
。
我知道如何使用扩展来扩展 joi 以添加新的自定义类型,但是这样做我无法将新类型与现有类型结合起来。
我希望能够执行joi.boolean().myrule()
和joi.string().myrule()
以及任何其他现有类型。 我该怎么做? 如果它有所作为,我将它与最新版本的 joi 一起使用。
有没有办法做joi.any.extend()
向any()
() 添加新规则而不是joi.extend()
(添加新类型)。
我看到了代码,但我认为这是不可能的(如果我错了,请纠正我)。 您可以做的最接近的是: 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()
) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.