Search code examples
node.jsexpressjoi

How can I add validation in Joi that old and new passwords should not be same?


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?


Solution

  • 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(),
      }),
    };