【发布时间】:2021-11-18 20:31:04
【问题描述】:
我想创建一个扩展来清理字符串输入并去除 html 标签。
为此,我使用sanitize-html npm 包。
这是我迄今为止尝试过的。
const sanitizeHtml = require('sanitize-html');
module.exports = function htmlStrip(joi) {
return {
type: 'htmlStrip',
base: joi.string(),
messages: {
htmlStrip: 'Should not contain any html tags.',
},
validate(value, helpers) {
const clean = sanitizeHtml(value, {
allowedTags: [],
allowedAttributes: {},
});
if (clean) {
return clean;
}
return { value, errors: helpers.error('htmlStrip') };
},
};
};
但我遇到了错误。
TypeError: Joi.string(...).trim(...).htmlStrip 不是函数
我也尝试过如下传递规则对象,但仍然遇到同样的错误。
const sanitizeHtml = require('sanitize-html');
module.exports = function htmlStrip(joi) {
return {
type: 'htmlStrip',
base: joi.string(),
messages: {
htmlStrip: 'Should not contain any html tags.',
},
rules: {
htmlStrip: {
validate(params, value, state, options) {
const clean = sanitizeHtml(value, {
allowedTags: [],
allowedAttributes: {},
});
if (clean) {
return clean;
}
return this.createError('string.htmlStrip', { value }, state, options);
},
},
},
};
};
我正在关注here 提到的文档。
这就是我使用扩展验证器的方式。
const Joi = require('@hapi/joi').extend(require('@hapi/joi-date')).extend(require('../utils/sanitize-html-joi'));
const validateAddressCreateData = (data) => {
const schema = Joi.object({
address: Joi.string().trim().htmlStrip().required(),
label: Joi.string()
.required(),
});
return schema.validate(data);
};
【问题讨论】:
-
请包含完整的错误堆栈。这样可以更容易地查看错误的来源。
-
@Molda 添加了弹出错误的代码。
标签: javascript node.js joi