我尝试将表单验证脚本同时暴露给router.post
中的router.get
和router.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();
...
});