如何在 Express (NodeJS) 中验证和处理表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5555053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:00:01  来源:igfitidea点击:

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

formsnode.jsexpress

提问by fadedbee

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

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.

我真的在寻找与 Django 表单中类似的抽象级别 - 即模板中的验证和错误报告。

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

如果可以在客户端使用相同的验证,那就太好了。

Has anyone used, or written, anything good?

有没有人用过或写过什么好东西?

采纳答案by Zikes

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.

看起来有一个位于https://github.com/caolan/forms的模块。我从未使用过它,但它似乎功能齐全。

回答by chovy

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

这看起来也可行,仍在开发中: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
};