是否有任何 JS 智能 json 模式验证器,例如 Joi,但存在动态自定义错误?



我想轻松验证用户的输入。

例如,当我询问用户的名字时,可能需要大量代码才能真正使其得到良好的验证。

我想要一些可以在前端和后端使用的东西 - 无需更改验证结构。

我需要能够抛出自定义的详细错误,如下所示:

let schema = Joi.object.keys({
first_name: Joi.string("Required to be a string")
.noNumbers("Should not contain numbers")
.minlenth(2, "At least 2 chars")
.maxlength(10, "Maximum 10 chars")
.required("Required field"),
last_name: Joi.string("Required to be a string")
.noNumbers("Should not contain numbers")
.minlenth(2, "At least 2 chars")
.maxlength(10, "Maximum 10 chars")
.required("Required field"),
});

不幸的是,上述方法不起作用 - 因为 Joi 不是这样工作的。

也许有一个好的 JSON 模式验证器可以轻松有效地验证用户的输入而不会浪费时间 - 同时让用户清楚?

您可以使用 JOI。在下面的示例中,我直接覆盖错误:

return Joi.object()
.keys({
str: Joi.string()
.min(2)
.max(10)
.required()
.error(errors => errors.map((err) => {
const customMessage = ({
'string.min': 'override min',
'string.max': 'override max',
})[err.type];
if (customMessage) err.message = customMessage;
return err;
})),
});

我重新命令您使用一个函数,考虑到所有请求的错误消息都是相同的:

function customErrors(errors) {
return errors.map((err) => {
const customMessage = ({
'string.min': 'override min',
'string.max': 'override max',
})[err.type];
if (customMessage) err.message = customMessage;
return err;
});
}
return Joi.object()
.keys({
str: Joi.string()
.min(2)
.max(10)
.required()
.error(customErrors),
});

编辑:

// This
const customMessage = ({
'string.min': 'override min',
'string.max': 'override max',
})[err.type];
if (customMessage) err.message = customMessage;

// Equals this
let customMessage = false;
if (err.type === 'string.min') customMessage = 'override min';
if (err.type === 'string.max') customMessage = 'override max';
if (customMessage) err.message = customMessage;

// Equals this
if (err.type === 'string.min') err.message = 'override min';
if (err.type === 'string.max') err.message = 'override max';

相关内容

最新更新