What's the best way to implement a validation check in Joi to ensure that the new password is not the same as the

Currently, I am in the process of creating Apis utilizing NodeJS and ExpressJS with Joi for schema validation. In one instance, I have a resetUserPinCode controller where I need to ensure that the oldPinCode and newPinCode values are not identical:

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())
      .valid(Joi.ref('oldPinCode'), { invert: true }).required(),
  }),
};

Although I can implement a check within the resetUserPinCode function to verify that oldPinCode and newPinCode are different, I would prefer to include this validation directly into my Joi schema. Is there a method available to accomplish this within the Joi schema itself?

Answer №1

To implement this feature, you can utilize the Joi.disallow() method as demonstrated below.

const updateUserPassword = {
  body: Joi.object().keys({
    username: Joi.string().required(),
    oldPassword: Joi.alternatives().try(Joi.string(), Joi.number()).required(),
    newPassword: Joi.alternatives().try(Joi.string(), Joi.number()).disallow(Joi.ref('oldPassword')).required(),
  }),
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: JSON parsing error - Unexpected token at the start of the JSON data when using JSON.parse() function

Backend code router.route('http://localhost:5007/api/media') .post(mediaCtrl.saveMedia) async saveMedia(req, res) { let file = req.files.file let ext = req.body.extension let path = req.body.path if(_.isNull(file) || _.isEmp ...

What is the ideal project layout for a React and Node.js application?

With all the latest trends in the JS world, it can be a bit overwhelming to figure out the best way to organize files and folders for a project. While there are some examples from Facebook on GitHub, they tend to be quite basic. You can also check out som ...

Error in React JS: SyntaxError - "Unexpected token '?'"

Following the guidelines on this website, I successfully set up a new reactJS application, proceeded to run npm i && npm run dev and encountered the following error message: /home/www/node_modules/next/dist/cli/next-dev.js:362 showAll ...

Having issues displaying the & symbol in HTML from backend data

I recently worked on a project using express handlebars, where I was fetching data from the YouTube API. However, the titles of the data contained special characters such as '# (the ' symbol) and & (the & symbol). When attempting to render the ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

Node.js MySQL REST API query fails to execute

I am developing a login/sign up API using nodejs, express, and mysql. Despite receiving the "Successful Sign Up!" message without any errors during testing, the user table in the database remains empty. Below is the query I am attempting to execute: con. ...

What is the process for updating a value on a client site with mongodb?

I am currently using a combination of React for the front-end and Node.js with MongoDB for the back-end. In my project, I have developed a custom hook to fetch data. Below is the code snippet for this custom hook: import { useEffect, useState } from " ...

Pass the JSX data as JSON from the Express backend and showcase it as a component in the React frontend

I am currently developing a basic react front-end paired with an Express backend. Is it possible for me to have express send JSX data as JSON so that I can fetch it in react and utilize it as a component? Right now, I am sending JSON data and successfully ...

TurboRepo initiates the web server and promptly closes down without any issues

I have a turbo-repo set up using pnpm, and I am attempting to launch the React frontend for one of my clients with the following command: npx turbo run start --filter=testclient When executing this command, the output is as follows: • Packages in scope: ...

Leveraging Promises for Concurrent In-Memory Processing

We are currently working on a project that involves processing approximately 5,000 objects, with each object requiring between 200-500 milliseconds to process. One of the developers on our team has suggested utilizing promises to handle the concurrent proc ...

What is preventing this POST request from successfully resolving and returning a 200 status code, despite the fact that the database is being updated?

I am a beginner in web development and facing an issue with writing a post request in Express using MongoDB as the database. The problem is that even though the document is created in the database, it does not return a 200 status code. Below is the functi ...

Display of saved collection in Mongoose response

Currently, I am managing an Express application that interacts with a MongoDB through Mongoose. The main functionality involves a basic content management system that allows for updating values on specific pages. Strangely, when changes are made on my stag ...

The expiration time of the JWT signed token remains unchanged in the browser application even after being updated in the code

Here is the code snippet: const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: '1d' }); res.cookie('token', token, { expiresIn: '1d' }); Initially, everything was functioning properly with t ...

Struggling with breaking down passport.js into modules in node.js

Hey there, I'm facing a bit of an issue with my login route: var express = require('express'); var router = express.Router(); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; re ...

Issue encountered while attempting to install Express using nodejs

Currently, I am facing issues while trying to install express using nodeJS. The errors indicate that my directories need to be renamed. Even after running npm init in the project folder, which seems to be set up correctly, I encounter problems. The command ...

Retrieving data from various schemas using Node.js

I am managing two schemas, one for employees (parent) and the other for assessments (child). Each assessment is linked to an employee ID with a pass percentage. Here are some sample data: employees : [ { "_id": 12345, "name": "David", "eval ...

Unable to install protractor using npm due to an error

Encountering an error while trying to install protractor: C:\Users\andreir\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\node_modules\ws\node_modules\utf-8-vali ...

Error in Moongose: Using .populate on a key with whitespace is not functioning as expected

I am currently working with Express and Mongoose for database operations. I have encountered an issue where attempting to populate a path with a key that contains a whitespace causes it to be ignored. MongoDB Model: const OrgCrimeSchema = new Schema({ g ...

What is the purpose of using the http module to specify the port when the app.listen function already sets the

var express = require("express"); var app = express(); // This code sets the port to 8080 by default, or else it will use the environment-specific port. app.set('port', process.env.PORT || 8080); app.get('/', function(req, res){ r ...

The command prompt is attempting to access a user directory that is not present

During my attempt to upgrade node.js, I encountered an issue where the nvm command was using a USERNAME that does not exist on my computer. This is different from the USERNAME I typically use. Here is the error message ...