Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

335
Visualizações
Joi validation - allow field to be optional but when supplied must be a positive integer

I have a field in a JOI schema that I would like to be optional (i.e. undefined is accepted, and null is also accepted), however if a value for it is supplied, it must be a positive integer. How might I go about achieving this?

Here is what I have tried so far, with the field to validate being "capacity" however it does not seem to work, it appears the ".when" statement is just being ignored:

const divebarSchema = joi.object({
  divebar: joi
    .object({
      title: joi.string().required(),
      capacity: joi.optional().allow(null),
      description: joi.string().required(),
      location: joi.string().required(),
      image: joi.string().optional().allow(""),
      map: joi.string().optional().allow(""),
    })
    .required()
    .when(joi.object({ capacity: joi.exist() }), {
      then: joi.object({ capacity: joi.number().integer().min(0) }),
    }),
});

Before the above I originally had no .when and instead the capacity rule was:

  capacity: joi.number().optional().allow(null).integer().min(0),

However that also did not work, it kept throwing the error "must be a number" when submitting a null value.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

According to Joi documentation optional does not include null you need to use allow

capacity: Joi.number().optional().integer().min(0).allow(null)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda