问题
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