我想使用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');
}
});