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

243
Visualizações
How to create a conditional validator with mongoose validators

I currently have two validators running with my Mongoose Schema, however, I want to always execute the first one and the second validator I want executed based on a conditional, if a hyphen is present or not in the number string. How would I go about doing this?

Here is my code in question:

const manyValidators = [
    { validator: function(number) {
        const numberLength = number.length
        return ((numberLength >= 9 && number.includes('-') === true) || (numberLength >= 8 && number.includes('-') === false ))
    },
    message: "You must have at least 8 characters if you do not have a hyphen but 9 characters if you do."
    }, 
    { validator: function(number) {
        return (number.indexOf('-') === -1 && ((number.indexOf('-') === 2 || number.indexOf('-') === 3)))
    },
    message: "There should be at least 2 or 3 characters before the hyphen"
    }
]

const personSchema = new mongoose.Schema({
    id: String,
    name: {
        type: String,
        minlength: [3, "Names must be of 3 characters minimum."],
        required: true
    },
    number: {
        type: String,
        validate: manyValidators,
        required: true
    }
})

The first validator consists of the "You must have at least 8 characters if you do not have a hyphen but 9 characters if you do." string and the second one is the hyphen validator.

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

0

I am so blind, I realized that the validators themselves are functions so I added an if statement before the return statement in question to confirm if a hyphen is present or not via indexOf

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