开发者

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

开发者 https://www.devze.com 2023-02-22 11:22 出处:网络
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

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

精彩评论

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