The below schema allows me to have the optionalField
required if value
is set to option1
but if value is set to option2
then optionalField
can be set to anything the user desires. Instead, I want the validation to fail if value
is set to anything other than option1
and optionalField
is passed in.
const validValues = ['option1', 'option2']
const sampleSchema = new mongoose.Schema({
value: {
type: String,
enum: validValues,
required: true
}
optionalField: {
type: Number,
required: function() { return this.value === 'option1' }
// validation should fail if this property is passed in when value is anything but option1
}
})
Joi has an excellent way to achieve this using Joi.forbidden()
:
const validValues = ['option1', 'option2']
const schema = Joi.object({
value: Joi.string().valid(...validValues).required(),
optionalField: Joi.string().when('value', { is: 'option1', then: Joi.required() otherwise: Joi.forbidden() })
})
If I validate with this schema and optionalField
is passed in to Joi, the validation will fail unless value
is option1
.
I am hoping to find a way to achieve the same in Mongoose.
Thank You!