[英]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.