Express validation, custom async checking

♀尐吖头ヾ 提交于 2020-03-23 02:30:22

问题


So, I have done a pretty good amount of research on this and I am having some issues.

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

I am having issues with the email check. It seems to be working for the most part but it is not returning an error. I know I am using the same email, and it is pulling it correctly. But the validation is not working. Any ideas?


回答1:


Okay this time I got it working, for real:

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

And:

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



回答2:


Yes, William your answer is completely correct I just wanted to add the reason why for any other curious minds.

If we use asyncFunction in custom validator we have to return a Promise object. When validation works we don't need anything from the function hence works invalid cases, but return false will not work but Promise.reject() will.

Also, you can use Promise.resolve() to completely correct your code.



来源:https://stackoverflow.com/questions/53693650/express-validation-custom-async-checking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!