I am using express-validator for validation. In my controller I have a method for adding new pictures to the database. Here is my code:
function createPicture(req, res) {
req.checkBody('title', `The title can't be empty.`).notEmpty();
req.checkBody('image', 'You must select an image.').notEmpty();
let errors = req.validationErrors();
if (errors) {
res.json({errors: errors});
} else { ... }
The code works for the title field however no matter if I select an image or not - I still get a validation error about it. How can I validate file input? I just want it to be required.
const Validator = require('validatorjs'); const validator = async (body, rules, customMessages, callback) => { const validation = new Validator(body, rules, customMessages); validation. passes(() => callback(null, true)); validation. fails(() => callback(validation. errors, false)); }; module.
According to the official website, Express Validator is a set of Express. js middleware that wraps validator. js , a library that provides validator and sanitizer functions. Simply said, Express Validator is an Express middleware library that you can incorporate in your apps for server-side data validation.
Object schema validation. express-validator and joi can be primarily classified as "npm Packages" tools. express-validator and joi are both open source tools. It seems that joi with 17.7K GitHub stars and 1.41K forks on GitHub has more adoption than express-validator with 5.1K GitHub stars and 535 GitHub forks.
I had the same problem, the below code will not work since express-validator only validates strings
req.checkBody('title', 'The title can't be empty.').notEmpty();
req.checkBody('image', 'You must select an image.').notEmpty();
You'll need to write a custom validator, express-validator allows for this, okay this is an example of one
//requiring the validator
var expressValidator = require('express-validator');
//the app use part
app.use(expressValidator({
customValidators: {
isImage: function(value, filename) {
var extension = (path.extname(filename)).toLowerCase();
switch (extension) {
case '.jpg':
return '.jpg';
case '.jpeg':
return '.jpeg';
case '.png':
return '.png';
default:
return false;
}
}
}}));
To use the custom validator, do this first to make sure empty files will not throw undefined error:
restLogo = typeof req.files['rest_logo'] !== "undefined" ? req.files['rest_logo'][0].filename : '';
Finally to use your custom validator:
req.checkBody('rest_logo', 'Restaurant Logo - Please upload an image Jpeg, Png or Gif').isImage(restLogo);
Thanks for your question, hope this will help someone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With