I am trying to use express-validator to validate the req.body before sending a post request to insert data to postgres.
I have a route file, controller file and I want to carryout validation in a file called validate.js. Meanwhile, I have installed express-validator and in my server.js I have imported it. Other resources I come across seem to implement the validation in the function that contains the logic for inserting the data.
//server.js
....
import expressValidator from 'express-validator';
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator);
//route.js
import express from 'express';
import usersController from './controller';
const router = express.Router();
router.post('/createuser', usersController.createUser);
//controller.js
createUser(req, res){
// ...
const { firstName, lastName, email, password } = req.body;
//code to insert user details to the database
}
//validator.js
import { check } from 'express-validator/check';
module.exports = [check('email').isEmail()];
I expect to implemet the validation in a file called validator.js to, say, validate the email before inserting to the database