How to check if email address is already in use or not using express-validator in Node.js ?

We use ‘express-validator’ middleware to implement this functionality.

Command to install express-validator:

npm install express-validator

Steps to use express-validator to implement the logic:

  • Install express-validator middleware.
  • Create a validator.js file to code all the validation logic.
  • Validate email by validateEmail : check(’email’) and chain on all the validation with ‘ . ‘
  • Use the validation name(validateEmail) in the routes as a middleware as an array of validations.
  • Destructure ‘validationResult’ function from express-validator to use it to find any errors.
  • If error occurs redirect to the same page passing the error information.
  • If error list is empty, give access to the user for the subsequent request.

{ check } = require(‘express-validator’)

const repo = require(‘./repository’)

 

module.exports = {

    validateEmail: check(’email’)

        // To delete leading and triling space

        .trim()

  // Normalizing the email address

        .normalizeEmail()

        // Checking if follow the email

        // address format or not

        .isEmail()

 

        // Custom message

        .withMessage(‘Invalid email’)

        // Custom validation

        // Validate email in use or not

        .custom(async (email) => {

            const existingUser =

                await repo.getOneBy({ email })

            if (existingUser) {

                throw new Error(‘Email already in use’)

            }

        })

}

Leave a comment

Your email address will not be published. Required fields are marked *