快速验证,自定义异步检查 [英] Express validation, custom async checking
本文介绍了快速验证,自定义异步检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我对此进行了大量研究,并且遇到了一些问题.
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?
推荐答案
这次我确实可以正常工作了:
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.');
并且:
// 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');
}
这篇关于快速验证,自定义异步检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文