So I have some posts validation using @hapi/joi 17.1.1 and in there I have two fields: textfield and picture. Im not requring any of the fields yet still it is saying that picture is required.
posts validation
module.exports.postsValidation = (data) => {
const schema = Joi.object({
textfield: Joi.string().max(280),
picture: Joi.string(),
});
return schema.validate(data);
};
posts.js (where im using validation)
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);
}
});
when I log out the error it says this
[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]
}
]
}
Can anyone please tell whats going on?
CodePudding user response:
This is because you are sending the prop picture
from the FE side and it's an empty string ''
. You should add an .allow('')
your validation picture: Joi.string().allow('')
if you want to save an empty string inside the DB or change the FE side to not send the picture
prop at all if the string is empty.
CodePudding user response:
Just in case the value is null too
module.exports.postsValidation = (data) => {
const schema = Joi.object({
textfield: Joi.string().max(280),
picture: Joi.string().allow("", null),
});
return schema.validate(data);
};