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

242
Views
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 answers
Answer question

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 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!