gpt4 book ai didi

javascript - 有没有像 Joi 这样的 JS 智能 json 模式验证器,但是有动态自定义错误?

转载 作者:行者123 更新时间:2023-11-30 20:06:40 25 4
gpt4 key购买 nike

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

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

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

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

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';

关于javascript - 有没有像 Joi 这样的 JS 智能 json 模式验证器,但是有动态自定义错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52849837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com