I've encountered an issue with posts validation using @hapi/joi 17.1.1. In my schema, I have two fields: textfield and picture. Although both fields are not required, the validation is still indicating that the picture field is mandatory.
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 validation is used)
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);
// Creating a new post
const newPost = new Post({
textfield: req.body.textfield,
picture: req.body.picture,
ownerId: req.user._id,
});
// Saving the new post
await newPost.save();
res.json(newPost);
} catch (error) {
res.sendStatus(500);
}
});
The error message indicates that:
[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]
}
]
}
If anyone could help shed some light on what might be causing this issue, I would greatly appreciate it.