Alex Rivera | Logout

How to validate and handle a form in Express (NodeJS)

Asked 2011-04-05T16:18:55.587
21

Is there a preferred form handling and validation library for Express?

I'm really looking for a similar level of abstraction as is found in Django forms - i.e. validation and error reporting in the template.

If the same validation could be used on the client side, that would be great.

Has anyone used, or written, anything good?

Edit
Report

1 Answer

7

This also looks viable and is still being developed: https://github.com/ctavan/express-validator

Here's an example of validating a form submission (login post request):

exports.login.post = function(req, res){
  req.assert('username', 'Enter username').notEmpty();
  req.assert('password', 'Enter password').notEmpty();
  res.locals.err = req.validationErrors(true);

  if ( res.locals.err ) {
    if ( req.xhr ) {
      res.send(401, { err: res.locals.err });
    } else {
      res.render('login', { err: res.locals.err });
    }

    return;
  }

 //authenticate user, data is valid
};
answered 2012-09-22T04:10:12.990

Your Answer