Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Joi requiring fields when it shoudnt be

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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);
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!