node.jsexpressexpress-validator

check if any other users have the same email in express-validator


User wants to update their email, i have to check if any other users have it, if so then i return a message saying the email is already in use, i have to check all users but not the user who want to change it

    custom: {
      options: async (email) => {
        const isExist = await fetchUserByEmailOrID(email);
        if (isExist.length) {
          throw new Error("A user already exists with this email address");
        }
      },
      bail: true,
    },

Currently this will throw the error if user changes his name, phone number or any other data because it will check for the user email, how to fix it


Solution

  • Well, you have two possible solutions, if you have a unique constraint on the email column, you can try to update the user info and if it throws an error, you can check whether it's a duplicate error or not, if it was a duplicate error you can show the proper error message to the user.

    The other solution would be what you demonstrated in your sample code, checking if someone exists with that email.

    However I highly recommend not doing it in your validator, the validator should validate and sanitize the user input, which is out of the scope of the validator layer.

    You need to provide information about the ORM you use and the design of your database if you need sample code for each solution