我正在使用 Node.js(使用 Express)编写一个非常基本的注册表单,并且我正在尝试找到提供基本表单验证的最简单方法。我选择了“Express-Validator”,这似乎做得很好。但是,我的目标是简单地显示所需的任何验证消息,并保留用户输入的值。
似乎请求信息没有回到 res.render 中,我想这是有道理的。但是,我到处寻找我能想到的地方,但找不到任何讨论如何在显示错误消息后保持表单字段填充的参考。
下面是一个描述我的方法的小片段:
post: function(req, res){
var userName = req.body.username;
var password = req.body.password;
//Validate input
req.assert("username", 'Invalid email address.').isEmail();
req.assert("password", 'Password cannot be empty.').notEmpty();
req.assert("passwordConfirm", 'Passwords entered do not match!').equals(password);
//Make sure we have no validation errors
var pageErrors = req.validationErrors();
if(!pageErrors)
{
userModel.CreateUser(userName, password, function(err){
if(err)
{
//there was a problem inserting new user... probably already exists
//will need to check the error to confirm
var dbErrorMessage = "Could not insert record into database!";
if(err.code === 11000)
{
//this is a duplicate entry
dbErrorMessage = "A user with that email address already exists!";
}
res.render('register.html', { pageErrors: [{msg: dbErrorMessage }]});
}
else
{
res.render('register.html', { successMessage: successMessage });
}
});
}
else
{
res.render('register.html', { pageErrors: pageErrors });
}