I am validating my form with express-validator...if I have errors, what's the best way to stop the form from submitting and go back to the login page. This is what I have, which works, just looking for best way to handle this (not sure about the return statement).
//routes/index.js
exports.login.post = function(req, res){
req.assert('username', 'Please enter username').notEmpty();
req.assert('password', 'Please enter password').notEmpty();
res.locals.errors = req.validationErrors(true);
if ( res.locals.errors ) {
console.log(res.locals.errors);
var d = { title: 'Login' };
res.render('login', { d: d });
return;
}
//do login here if no errors
};
I also do not know how to get at original values in form template (ejs).
I tried passing req.param in, but it is empty.
The err object only has those fields with errors, so if I enter username, but leave password blank, I only get password in err object, not username...so I need req.param.username, but when I pass { q: req.param} and use <%= inspect(q) %> it is empty.
update: req.body gives me the original post parameters to pre-populate the form. so you need err stack and req.body stack to have a good experience.
What I suggest doing is using something like flashify to set a flash notification and redirect the request back to the view.
So you can do something like:
if ( res.locals.errors )
{
res.flash('error','bad username/password');
req.session.formData = req.body;
res.redirect('back');
}
Then inside the view, you just check if flash.error
exists, and output the message if it does, then: <%= flash.error %>
:)
This is what I do
app.post('/form_process',validateForm,form.handle)
function validateForm(req,res,next){
req.assert('username', 'Invalid Username').notEmpty().isAlpha();
req.assert('password', 'Invalid Password').notEmpty().isAlpha();
var errors = req.validationErrors();
if (errors) {
//res.send(errors,500);
var original_values = {
username : req.param('username'),
password : req.param('password')
}
res.render('login',{errorMsg:errors,original:original_values,title:"Login error"})
return;
}
else next()
}