vendredi 6 novembre 2015

Dealing with validation errors in Express

If I have a home page at / with multiple forms on it, like a login form and a registration form, how would I properly handle validation? Let's say the registration form POSTs to /register and there are errors, how would I redisplay / with the error messages?

If I do res.render('index.html', context), the home page appears but under the URL /register rather than /, which is wrong. And if I do res.redirect('/') then I lose the validation errors that I wanted to display on the home page. So what's the right way to do this?

app.get('/', function (req, res) {
  ...
  res.render('index.html', context);
});

app.post('/register', function (req, res) {
  ... // Collect validation errors of registration form
  if (errors) {
    res.render('index.html', context);
  }
});

Aucun commentaire:

Enregistrer un commentaire