问题
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
回答1:
Here is the way i use express-validator. I have a file validator.js
where i have validation logic for many routes. For example:
validator.js
const { check } = require('express-validator/check');
exports.createUser = [check('email').isEmail()];
exports.anotherRoute = [// check data];
exports.doSomethingElse = [// check data];
Now in your route file you require the validator.js fileconst validator = require("./validator"); // or where your file is located
and use the validation logic you want as a middleware. For example:
route.js
//
router.post('/createuser', validator.createUser, usersController.createUser);
Last, inside your controller you have to check for possible errors created during validation, after requiring validationResult
.
controller.js
const { validationResult } = require('express-validator/check');
exports.createUser(req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
// do stuff here.
}
Also, you don't have to use app.use(expressValidator);
in your server.js file
来源:https://stackoverflow.com/questions/55772477/how-to-implement-validation-in-a-separate-file-using-express-validator