Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda