I'm trying to extend expressValidator to add my custom rule for checking if req.files is coming in as an image. Because express-validator uses node-validator, and node-validator parses the request body for the input parameter:
req.body.email is passed in as req.assert('email', 'Please enter a valid Email').isEmail(), so anything passed into req.assert() with express-validator needs to be the parameter name.
This is where I'm running into a problem, because I have my method I wrote here:
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;
};
But I can't just do req.assert('avatar', 'Please enter a valid image type').isImage() because for one, I need to pass in the req.files.avatar.type. With req.assert(), the first parameter expects a string.
If I do give it the string: e.g. req.assert(req.files.avatar.type, 'Please enter a valid image type').isImage() in my error message object, it'll show this:
{ 'image/png':
{ param: 'image/png',
msg: 'Please enter a valid image',
value: undefined }
}
When it should be showing this:
{ 'avatar':
{ param: 'avatar',
msg: 'Please enter a valid image',
value: 'image/png' }
}
Recently I did something similar. But my approach is a little different, more kinda hack. But since no one answered, I will try to help :)
I wrote a generic error generation vaildator.prototype
expressValidator.Validator.prototype.genError = function() {
this.error(this.msg);
return this;
};
Then while validating,
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);
.......
This works for me perfectly. Your approach is of-course better, but this works as well :)