开发者

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

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

I'm really looking for a similar level of abst开发者_如何学JAVAraction 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?


It looks like there's a module for this located at https://github.com/caolan/forms. I've never used it, but it seems fairly full featured.


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
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜