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

338
Visualizações
Conditional array items with Joi

I have an issue to create Joi schema for this input

{
  projects: ["*","ABC123","ABC456"]
}

With the input above, it should throw an error.

I did try to use Joi.alternatives() like this

const schema = Joi.object({
  projects: 
    Joi.array()
    .items(
      Joi.alternatives(
        Joi.string().equal('*'), 
        Joi.string().regex(new RegExp(/^ABC_([0-9]{3,3})$/))
      )
    )
})

but it appears to allow both ["*"] and ["ABC123","DEF456"] together. I wanted it to be either ["*"] or ["ABC123","DEF456"], else it will be an error.

How can I actually achieve it by using Joi?

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

0

You can try something like this:

const schema = Joi.object({
  projects: Joi.alternatives(
    Joi.array().length(1).items(
      Joi.string().equal('*')
    ),
    Joi.array().items(
      Joi.string().regex(/^ABC[0-9]{3}$/)
    )
  )
});

That is, havingh two alternative array schemas instead of having a single array schema with alternative schemas of elements.

The .length(1) is there to reject values like ["*", "*"] if you want to reject arrays like that, but could be omitted otherwise.

Also, the regex could be written in a simpler way so I simplified it, but I guess that it was just an example so that is not so important. What is important though is that i removed the underscore ("_") from the regex, because a regex in your example didn't match values like "ABC123" in your example but e.g. "ABC_123".

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