Validating multipart-form data parsed through multiparty and validation through express-validator

自古美人都是妖i 提交于 2019-12-25 14:24:10

问题


I am sending multipart form data and saving it on server but data is being saved without any validation. To parse the data I have used multiparty and express-validator for post data valdation but i am saving data without any validation.

To send this data to the server I am using postman.

my code on sever side is as follows

exports.signup = function(req, res) {
  var form = new multiparty.Form();

  // Validation checks
  req.assert('first_name', 'first name is required').notEmpty(),
  req.assert('last_name', 'last name is required').notEmpty();
  req.assert('email', 'valid email is required').notEmpty().isEmail();
  req.assert('password', 'password field is required').notEmpty().len(6, 10);

  var errors = req.validationErrors();
  if( !errors){
      form.parse(req, function(err, body , files) {
          ////////
          code to save the data on server goes here
      });

  }
  else if (errors) {
      return res.status(400).send({
          'error': errors
      });
  }
};

回答1:


Currently, you're trying to validate body fields before they are parsed, which isn't possible.

You have to move your req.assert() and req.validationErrors() lines inside your form.parse() callback. For example:

exports.signup = function(req, res) {
  var form = new multiparty.Form();
  form.parse(req, function(err, body, files) {
    if (err)
      return res.status(500).end();

    req.body = body;

    // Validation checks
    req.assert('first_name', 'first name is required').notEmpty(),
    req.assert('last_name', 'last name is required').notEmpty();
    req.assert('email', 'valid email is required').notEmpty().isEmail();
    req.assert('password', 'password field is required').notEmpty().len(6, 10);

    var errors = req.validationErrors();

    if (errors) {
      res.status(400).send({
        'error': errors
      });
    } else
      res.status(200).end();
  });
};


来源:https://stackoverflow.com/questions/32517220/validating-multipart-form-data-parsed-through-multiparty-and-validation-through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!