node.js - 快速验证、自定义异步检查
问题描述
因此,我对此进行了大量研究,但遇到了一些问题。
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');
}
});
我在使用电子邮件检查时遇到问题。它似乎大部分都在工作,但它没有返回错误。我知道我使用的是同一封电子邮件,并且它正确地提取了它。但验证不起作用。有任何想法吗?
解决方案
好吧,这次我让它工作了,真的:
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');
}
推荐阅读
- perl - 在 Perl 脚本中“使用”基于 Moose 的包
- matlab - 在Matlab中填充复平面中的区域
- laravel - 了解传递给 Vue 子组件的路由器视图的道具,道具数据未呈现
- javascript - Load dynamic Vue routes from json file
- c# - 画布 ui 操纵杆元素的 X 轴旋转不起作用,而 Y 轴在 Unity 中起作用
- sql - 当所有元组在重复项和原始元组中都相同时,如何删除重复项但保留一个?在PostgreSQL中
- exception - 程序从指定文本中删除字符时出现异常
- javascript - 如何不允许在 JavaScript 中连续按下两个键?
- reactjs - NPM 安装在这个 VSCode 项目中发疯,请指教
- c# - 仅发布模式下的 UWP 异常