I am building Apis using NodeJS & ExpressJS and Joi for schema validation.
Here is my Joi validation for my resetUserPinCode controller where I want to check that oldPinCode and newPinCode should not be the same:
const resetUserPinCode = {
body: Joi.object().keys({
phoneNumber: Joi.string().required(),
oldPinCode: Joi.alternatives().try(Joi.string(), Joi.number()).required(),
newPinCode: Joi.alternatives().try(Joi.string(), Joi.number()).required(),
}),
};
I can add check in resetUserPinCode function that oldPinCode and newPinCode are not same but I want to add that in my Joi validation schema. Is there any way I can add that validation in my Joi schema?
CodePudding user response:
Try using invalid()
:
const resetUserPinCode = {
body: Joi.object().keys({
phoneNumber: Joi.string().required(),
oldPinCode: Joi.alternatives().try(Joi.string(), Joi.number()).required(),
newPinCode: Joi.any()
.invalid(Joi.ref('oldPinCode'))
.alternatives()
.try(Joi.string(), Joi.number())
.required()
.options({
language: { any: { allowOnly: 'must not match previous pin code' } },
}),
}),
};
CodePudding user response:
This functionality can be achieved by using Joi.disallow()
as shown below.
const resetUserPinCode = {
body: Joi.object().keys({
phoneNumber: Joi.string().required(),
oldPinCode: Joi.alternatives().try(Joi.string(), Joi.number()).required(),
newPinCode: Joi.alternatives().try(Joi.string(), Joi.number()).disallow(Joi.ref('oldPinCode')).required(),
}),
};