因此,我使用@hapi/joi 17.1.1 進行了一些帖子驗證,其中有兩個欄位:文本欄位和圖片。我不要求任何欄位,但仍然說需要圖片。
帖子驗證
module.exports.postsValidation = (data) => {
const schema = Joi.object({
textfield: Joi.string().max(280),
picture: Joi.string(),
});
return schema.validate(data);
};
posts.js(我使用驗證的地方)
router.post("/create", authenticateToken, async (req, res) => {
try {
if ((req.body.textfield == "") & (req.body.picture == "")) {
return res.status(400).json("Fill one of the fields");
}
const { error } = postsValidation(req.body);
if (error) return res.status(400).json(error.details[0].message);
// Getting info for new post
const newPost = new Post({
textfield: req.body.textfield,
picture: req.body.picture,
ownerId: req.user._id,
});
// Saving new post
await newPost.save();
res.json(newPost);
} catch (error) {
res.sendStatus(500);
}
});
當我注銷錯誤時,它說
[Error [ValidationError]: "picture" is not allowed to be empty] {
_original: { textfield: 'sssss', picture: '' },
details: [
{
message: '"picture" is not allowed to be empty',
path: [Array],
type: 'string.empty',
context: [Object]
}
]
}
誰能告訴發生了什么?
uj5u.com熱心網友回復:
這是因為您picture從 FE 端發送道具,它是一個空字串''。如果您想在資料庫中保存一個空字串,或者如果字串為空,則將 FE 端更改為根本不發送道具,您應該添加.allow('')您的驗證。picture: Joi.string().allow('')picture
uj5u.com熱心網友回復:
以防萬一該值也為空
module.exports.postsValidation = (data) => {
const schema = Joi.object({
textfield: Joi.string().max(280),
picture: Joi.string().allow("", null),
});
return schema.validate(data);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/491741.html
標籤:javascript 表示 验证 乔伊
