Hafizi
Hafizi

Reputation: 39

Express-validator check if email existed with MySQL

Im using express-validator to check if the req.body entered is valid and to check if there is duplicate email in the MySQL database

Here is my code:

  router.post(
  "/signup",
  [
    body("uemail","email is not valid")
    .isEmail()
    .normalizeEmail()
    .custom(async (email, {req} )=>{

        const queryString = "SELECT uid FROM EarlyUsers WHERE `uemail` = ?";
        return await connection.query(queryString, [email], (err, rows, fields) => {
          if (err) {
            console.log(err)
          }else {
            if (rows.length != 0) {
              return false
            } else {
              return true
            }
          }
        });

    })
    ,
    body("uname").isLength({ min: 5 })
  ],
  authControllers.signUp
);

I dont know why this custom validator does not work. I've tried to throw new Error instead of return false, but it just crash the whole thing . I really need help with this

Upvotes: 0

Views: 2588

Answers (3)

hamid-davodi
hamid-davodi

Reputation: 1966

I found this solution to check that the email is not duplicate:

router.post('/register', 
    body('email').isEmail().normalizeEmail().withMessage('The email format is not correct.').custom((email) => {
    
            const queryString = `SELECT * FROM users WHERE user_email = "${email}"`;        
            
            return getFinalEmail(queryString).then(user => {
                console.log(user);
              if (user) {
                return Promise.reject('E-mail already in use');
              }
            });
            
    }),
    // -- other validations
    // .....
    (req, res) => {
    /* your code for this route */
 }); // end of router('/register')
 
 function getFinalEmail(param) {
    return new Promise(function(resolve, reject) {
        getEmailData(param, function(result) {
            console.log(result);
            resolve(result);
        });
    });
}

function getEmailData(query, callback) {

        database.query(query, function(error, data){
            if(data.length > 0) {
               return callback(true);
            } else {
               return callback(false);
            }
        });
    
}

In the above code users is the name of my table and user_email is the column that email data of users are stored.

Upvotes: 0

Muhammad Shahzad
Muhammad Shahzad

Reputation: 9652

I have achieved this way it might be helpful for others, I'm using sequelize :)

 const User = require("../../models/User");
 body('email', 'Invalid email').exists().isEmail().trim().escape().custom(userEmail=> {
            return new Promise((resolve, reject) => {
                User.findOne({ where: { email: userEmail } })
                .then(emailExist => {
                    if(emailExist !== null){
                        reject(new Error('Email already exists.'))
                    }else{
                        resolve(true)
                    }
                })
                
            })
        }),

Upvotes: 0

TKdevlop
TKdevlop

Reputation: 339

For it to work correctly instead of returning false you reject the Promise.

if (rows.length != 0) {
    return Promise.reject("user already exists.");
}

Upvotes: 1

Related Questions