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