I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
Before submitting a
it's not a bug with express-validators, it is the way how validators work in case of middlewares.
At the root level create a directory called utils and inside the directory a validation.js file and add your validation code in it:
utils/validation.js
const { check } = require('express-validator');
exports.addPostCheck = [
check('title', 'The title field id required')
.not()
.isEmpty(),
check('excerpt', 'The excerpt field id required')
.not()
.isEmpty(),
check('body', 'The full text field id required')
.not()
.isEmpty()
];
In the routes/dashboard.js include validation.js
const validator = require('../../utils/validation.js');
Change Line No: 16
From:
router.post('/post/add', dashboardController.addPost);
To:
router.post('/post/add', validator.addPostCheck, dashboardController.addPost);
In the controllers/admin/dashboard.js
Change Line No: 2
From:
const { check, validationResult } = require('express-validator');
To:
const { validationResult } = require('express-validator');
Remove Line Nos 29 to 39.
Reference
I have applied the solution provided by Saravanakumar T N with a small modification in messages.ejs.
I have: this in the controller:
exports.addPost = (req, res, next) => {
const errors = validationResult(req);
const post = new Post();
if (!errors.isEmpty()) {
req.flash('danger', errors.array());
req.session.save(() => res.redirect('../addpost'));
} else {
post.title = req.body.title;
post.short_description = req.body.excerpt
post.full_text = req.body.body;
post.save(function(err) {
if (err) {
console.log(err);
return;
} else {
req.flash('success', "The post was successfully added");
req.session.save(() => res.redirect('/dashboard'));
}
});
}
}
In the view:
<div id="messages" class="text-center">
<% Object.keys(messages).forEach(function (type) { %>
<% messages[type].forEach(function (message) { %>
<div class="alert alert-success <% if (type === 'danger') { %> alert-dismissible <% } %> alert-<%= type %>">
<% if (type === 'danger') { %>
<button type="button" class="close" data-dismiss="alert">×</button>
<%= message.msg %>
<%} else { %>
<%= message %>
<% } %>
</div>
<% }) %>
<% }) %>
</div>