扩展express-validator / node-validator以使用req.files

时间:2013-06-24 21:28:45

标签: javascript node.js validation express

我正在尝试扩展expressValidator以添加我的自定义规则,以检查req.files是否作为图像进入。因为express-validator使用node-validator,而node-validator正在解析输入参数的请求体:

req.body.email作为req.assert('email', 'Please enter a valid Email').isEmail()传入,因此使用express-validator传递到req.assert()的任何内容都需要是参数名称。

这是我遇到问题的地方,因为我有我在这里写的方法:

  expressValidator.Validator.prototype.isImage = function() {
    var type          = this.str,
        allowedTypes  = ['gif', 'jpg', 'jpeg', 'png'],
        allowed       = false;
    for (var i = 0; i < allowedTypes.length; i++) {
      if (type.indexOf(allowedTypes[i]) !== -1) {
        allowed = true;
      }
    }

    if (!allowed) {
      this.error(this.msg);
    }
    return this;
  };

但我不能只做req.assert('avatar', 'Please enter a valid image type').isImage(),因为对于其中一个,我需要传递req.files.avatar.type。对于req.assert(),第一个参数需要一个字符串。

如果我确实给它字符串:例如我的错误消息对象中的req.assert(req.files.avatar.type, 'Please enter a valid image type').isImage(),它会显示:

{ 'image/png':
   { param: 'image/png',
     msg: 'Please enter a valid image',
     value: undefined } 
}

何时应该显示:

{ 'avatar':
   { param: 'avatar',
     msg: 'Please enter a valid image',
     value: 'image/png' } 
}

1 个答案:

答案 0 :(得分:0)

最近我做了类似的事。但我的方法有点不同,更有点黑客。但既然没有人回答,我会尽力帮助:)

我写了一个通用错误生成vaildator.prototype

expressValidator.Validator.prototype.genError = function() {
  this.error(this.msg);
  return this;
};

然后在验证时,

var validate_profile = function(req, next) {
  async.series([
    function(callback) {
      req.assert('name', 'Please provide your name.').notEmpty().notNull();
      .........
    },
function(callback) {
  // Validate image size for profile_picture
  if(req.files.profile_picture && req.files.profile_picture.size === 0) {
    req.assert('profile_picture', 'Profile picture is required').genError();
  }
  if(req.files.profile_picture && req.files.profile_picture.size > 0) {
    imageMagick(req.files.profile_picture.path).size(function(err, size) {
    if (err) throw err;
    if(size.width < 1200) {
      req.assert('profile_picture', 'Profile picture should have atleast 1200px width').genError();
      callback(null);
    } else callback(null);
    .......

这对我很有用。你的方法当然更好,但这也有效:)

相关问题