I'm using Express-Validator
to validation my fields in forms on front, but exists()
function doesn't work.
I have another form (register form) where I'm using EV (Express-Validator) and in this case everything is okay, I'm doing the same with second form and here it validation doesn't work.
game.js (routing)
const app = require('express')();
const gameController = require('../controllers/gameController');
const { check } = require('express-validator/check');
module.exports = () => {
app.post('/add', [
check('title').exists().withMessage('The PBF Game with this title is actually in database'),
check('link').exists().withMessage('The PBF Game with this website link is actually in database')
], gameController.addGame);
return app;
}
gameController.js
const db = require('../models');
const { validationResult } = require('express-validator/check');
const validation = {
size: 40960,
type: 'image/png'
}
const path = 'uploads/';
module.exports = {
addGame(req, res, next) {
const { title, link, description } = req.body;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ status: res.statusCode, message: errors.array() });
} else if (req.files.icon.size > validation.size) {
return res.status(400).json({ status: res.statusCode, message: [{ 'msg': 'Your file has more than 50KB!' }] });
} else if (req.files.icon.mimetype !== validation.type) {
return res.status(400).json({ status: res.statusCode, message: [{ 'msg': 'You can upload only PNG files!' }] });
} else {
let file = req.files.icon;
file.mv(path + new Date().getTime() + '-' + file.name, err => {
if (err) {
return res.status(400).json({ message: [{ 'msg': err }] });
}
db.game.create({ title: title, link: link, icon: path + file.name, description: description, flag: false });
return res.status(200).json({ status: res.statusCode, message: 'The game has been added for verification. It should briefly appear in the selection field in the profile. If not, it means that the administrator has not approved the request.' });
});
}
}
}
Express-Validator not check if value exist in database and pass empty array to controller where I'm checking file and trying return correct response. User gets success response (if file is correct) but my server console display red alert about 'validation error' and no value is putting into database, but what I said before, user gets success response. Where is the problem?
Express validator can only validate the requests. It CAN NOT validate if a value is already present in database. For that, you need to query your database and check.
For example, the validation check('title').exists()
will check if title
field is present in the request, NOT in the database.