我正在尝试验证可以包含mustache语法的uri:
{{ key }}
因此它看起来可能像这样(首先是无效的URI):
http(s)://whatever.com/.../{{ key }}/...
我正在使用Joi
,看来Joi.string().uri()
不能允许更多字母。
我还检查了Joi.alternatives()
,但这将导致我创建自己的正则表达式,它可能不如Joi
中的正则表达式安全。
有什么想法吗?
答案 0 :(得分:0)
实际上,如果不完全重写它,就无法扩展内部符合RFC的正则表达式。
您已经注意到,这首先是一个无效的URI 。由于您似乎使用的是“简单的” Mustache持有人,并且没有条件标签,因此一种解决方法是为Joi提供一个已经渲染的URI(我们应该在第二个地方说吗?),就像这样:
const Mustache = require('mustache');
const Joi = require('joi');
// assuming objectToValidate.mustacheString holds a "potentially mustached URI"
/*async */function validateMyStuff(objectToValidate, myJoiSchema) {
// to catch standard and variable-like tags: {{standard}}, {{{variable}}} or {{&variable}}
const mustacheTypesToReplace = ['name', '&'];
// render into the object to validate
objectToValidate.mustacheString = Mustache.render(
objectToValidate.mustacheString,
// build a dummy view object
Mustache.parse(objectToValidate.mustacheString).reduce((accumulator, parsedItem) => {
if (mustacheTypesToReplace.includes(parsedItem[0])) {
accumulator[parsedItem[1]] = 'x'; // dummy data that won't break the RFC
}
return accumulator;
}, {})
);
// here the Joi.string().uri() shouldn't break unless URI is wrong
return Joi.validate(objectToValidate, myJoiSchema).then((validatedObject) => {
validatedObject.mustacheString = objectToValidate.mustacheString ; // set back the mustached data
return validatedObject;
});
}