[英]Is there any JS smart json schema validator, like Joi maybe, but with dynamic custom errors?
我想轻松验证用户的输入。
当我询问用户的名字时(例如),它可能需要大量代码行才能真正使其得到很好的验证。
我想要一些可以在前端和后端使用的东西 - 无需更改验证结构。
我需要能够抛出自定义的详细错误,如下所示:
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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.