我尝试将表单验证脚本同时暴露给router.post中的router.getrouter.use。我使用req.body.value从输入字段中获取数据。这在router.post中有效,但在router.use中无效。我收到此代码的以下错误消息(TypeError: Cannot read property 'length' of undefined):

router.use('/', (req, res, next) => {
  if(req.body.firstname.length === 0 || !req.body.firstname.match(/\D+/igm)) {
    var validateFirstname = false;
  } else {
    var validateFirstname = true;
  };

  if(validateFirstname === true) {
    console.log('SUCCESS: Form validated!');
  } else {
    console.log('ERROR: Form not validated!');
  };
  next();
});

有人可以向我解释为什么?无法将if else语句实现为router.use吗?稍后,当在router.get内验证表单时,将html div发送回用户将有巨大帮助。

更新:

我的验证问题是,在表单为空时要在加载后检查表单,这就是为什么返回undefined的原因。但是,在填充数据时,req.body可以在router.use中正常工作。除了页面加载以外,是否有其他方法可以检查输入字段?

最佳答案

作为一个很好的选择,我建议您使用express-validator模块来组织验证。

样本

var util = require('util'),
    express = require('express'),
    expressValidator = require('express-validator'),
    app = express.createServer();

app.use(express.bodyParser());

// this line must be immediately after express.bodyParser()!
app.use(expressValidator([options]));

app.post('/:urlparam', function(req, res) {
  // VALIDATION
  // checkBody only checks req.body; none of the other req parameters
  // Similarly checkParams only checks in req.params (URL params) and
  // checkQuery only checks req.query (GET params).
  req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
  req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
  req.checkQuery('getparam', 'Invalid getparam').isInt();
  ...
  var errors = req.validationErrors();
  ...
});

08-08 04:59
查看更多