使用expressjs验证器和mysql检查用户名和电子邮件是否已经存在

我想使用express-validator包检查mysql数据库中是否已经存在电子邮件。有关检查电子邮件的示例不适用于mysql数据库。

该代码已成功提交表单值,但跳过了检查。这是一个中间件,但是在插入数据库之前尚未实现该中间件。

我当前实现的解决方案来自stackoverflow。但仍然无法为我工作

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');
    }

});
wolaiwen_0 回答:使用expressjs验证器和mysql检查用户名和电子邮件是否已经存在

此代码对我有用:

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],fields) {
                if(!error){
                    console.log("EMAIL COUNT : "+results[0].total);
                    return resolve(results[0].total > 0);
                } else {
                    return reject(new Error('Database error!!'));
                }
              }
            );
        });
    }
本文链接:https://www.f2er.com/3166960.html

大家都在问