chovy chovy - 1 month ago 4x
Node.js Question

how to stop form submission with express.js and node

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 = 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 ) {
var d = { title: 'Login' };
res.render('login', { d: d });

//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 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.


This is what I do'/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) {
    var original_values = {
      username: req.param('username'),
      password: req.param('password')
    res.render('login', { errorMsg: errors, original: original_values, title: "Login error" })
  else next()