Search code examples
mysqlnode.jsexpressexpress-validator

check if username and email already exists with expressjs validator and mysql


I want to check if email already exist in mysql database using express-validator package to do this. The example about checking email is not for mysql database.

The code is submitting form values successfully but the checks are being skipped. This is a middleware but the middleware is not been implemented before inserting into the database.

The solution I currently implemented is from stackoverflow. But still not working for me

router.post("/register",[
    body('username').not().isEmpty().isLength({ min: 4 }).trim().escape(),
    //check if email is aleady existing in the database
    body('email').not().isEmpty().isEmail().normalizeEmail().custom(async (email, {req})=>{
        const getEmails = "SELECT * FROM users WHERE email=" + req.body.email;

        return await con.query(getEmails, [email], (error, rows, fields)=>{
            if(error){
                console.log("the email is not ok",error)

            }else{
                if (rows.length != 0) {
                    res.redirect('/guests/register');
                    return Promise.reject("user already exists.");
                }else{
                    return true;
                }
            }
        })
    }),//end check if email already exit
    body('phone').not().isEmpty().isLength({ min: 6 }),
    body('password').not().isEmpty().isLength({ min: 6 }),
    //check if password match
    body('passwordConfirmation').not().isEmpty().isLength({ min: 6 }).custom((value, { req }) => {
        if (value !== req.body.password) {
          throw new Error('Password confirmation does not match password');
        }
        return true;
    }),
      //check if password match  

], async function(req, res, next) {
    try{
        var usernames = req.body.username;
        var emails = req.body.email;
        var phones = req.body.phone;
        const hashedPassword = await bcrypt.hash(req.body.password, 10);

        let sql = "INSERT INTO `users` (username, email, phone, password) VALUES ('" + usernames + "', '" + emails + "', '" + phones + "', '" + hashedPassword + "')";

        con.query(sql, function (err, result) {
            if (err) throw err;
            console.log("1 record inserted, ID: " + result.insertId);
            res.redirect('/guests/login');
        })  

    }catch{
        //console.log("something is wrong", error)
        res.redirect('/guests/register');
    }

});

Solution

  • This code works for me:

    const express = require('express');
    const router = express.Router();
    const { check,validationResult } = require('express-validator');
    const bcrypt = require('bcrypt');
    const bcryptRounds = 10;
    
        router.post('/register', [
            check('username')
                .exists()
                .trim()
                .matches(/^[a-zA-Z\ö\ç\ş\ı\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü ]{3,16}$/)
                .withMessage('Invalid username!'),
            check('mentionName')
                .exists()
                .trim()
                .matches(/^(?=.*[a-z])[a-z0-9_]{3,15}$/)
                .custom(async mentionName => {
                    const value = await isMentionNameInUse(mentionName);
                    if (value) {
                        throw new Error('Mention name is already exists!!!');
                    }
                })
                .withMessage('Invalid mention name!!!'),
            check('email')
                .exists()
                .isLength({ min: 6, max: 100 })
                .isEmail()
                .normalizeEmail()
                .trim()
                .custom(async email => {
                    const value = await isEmailInUse(email);
                    if (value) {
                        throw new Error('Email is already exists!!!');
                    }
                })
                .withMessage('Invalid email address!!!'),
            check('password')
                .exists()
                .isLength({ min: 6, max: 16 })
                .escape()
                .trim()
                .withMessage('Invalid password!!!'),
            check('rePassword').exists().custom((value, { req }) => {
                if (value !== req.body.password) {
                  throw new Error('The passwords is not same!!!');
                }    
                return true;
              })
          ],
          function (req, res) {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                return res.status(422).json({ errors: errors.array() });
            } else {
                console.log("----->START USER REGISTRATION");
                const username = req.body.username;
                const mentionName = '@'+req.body.mentionName;
                const email = req.body.email;
                const pass = req.body.password;
                bcrypt.hash(pass, bcryptRounds, function(err, hash) {
                    console.log("HASH PASS : "+hash);
                    //INSERT USER
                });
            }
        });
    
        function isMentionNameInUse(mentionName){
            var conn = require('../../modules/mysql_db');
            return new Promise((resolve, reject) => {
                conn.query('SELECT COUNT(*) AS total FROM users_table WHERE m_name = ?', [mentionName], function (error, results, fields) {
                    if(!error){
                        console.log("MENTION COUNT : "+results[0].total);
                        return resolve(results[0].total > 0);
                    } else {
                        return reject(new Error('Database error!!'));
                    }
                  }
                );
            });
        }
    
        function isEmailInUse(email){
            var conn = require('../../modules/mysql_db');
            return new Promise((resolve, reject) => {
                conn.query('SELECT COUNT(*) AS total FROM users_table WHERE email = ?', [email], function (error, results, fields) {
                    if(!error){
                        console.log("EMAIL COUNT : "+results[0].total);
                        return resolve(results[0].total > 0);
                    } else {
                        return reject(new Error('Database error!!'));
                    }
                  }
                );
            });
        }