首页 > 解决方案 > 快速验证、自定义异步检查

问题描述

因此,我对此进行了大量研究,但遇到了一些问题。

router.post('/register', async (req, res) => {
const newUser = await usersDb();
// Define the user
const email = req.body.email;
const username = req.body.username;
const password = req.body.password;
const confirmPassword = req.body.confirmPassword;

// Start user already exist check
let userNameCheck = await newUser.findOne({ 'username': username});

req.check('email', 'Email is not valid.').isEmail()
  .custom(async value => {
    let emailCheck = await newUser.findOne({ 'email': value });
    console.log(emailCheck);
    console.log('Hmmm')
    if (emailCheck !== null) {
      return true;
    } else {
      return false;
    }
  }).withMessage('Email is already in use.');

//req.check('username', 'Username is required.').notEmpty();    
req.check('password', 'Password is required.').notEmpty();
req.check('confirmPassword', 'Confirm password is required.').notEmpty();

// Get errors
let errors = await req.validationErrors();
if (errors) {
   console.log(errors);
   res.render('index', {
    errors: errors
  });
} else {     
  console.log('Still bad');
}
});

我在使用电子邮件检查时遇到问题。它似乎大部分都在工作,但它没有返回错误。我知道我使用的是同一封电子邮件,并且它正确地提取了它。但验证不起作用。有任何想法吗?

标签: node.jsexpress-validator

解决方案


好吧,这次我让它工作了,真的:

req.check('email', 'Email is not valid.').isEmail()
  .custom(async value => {
    let emailCheck = await newUser.findOne({ 'email': value });
    if (emailCheck !== null) {
      console.log('User Exists');
      return Promise.reject();
    }
}).withMessage('Email is already in use.');

和:

// Get errors
const errors = await req.getValidationResult();
console.log(errors.mapped())
if (!errors.isEmpty()) {
   res.render('index', {
    errors: errors.mapped()
  });
} else {     
  console.log('Still bad');
}

推荐阅读