I'm sure this is not a problem instead I'm not using it the right way.
I want to validate user request body and according to documentation, all work is done in the route file. And I divided my work into routes and controllers files. I passed a validation middleware and it needs to be validated but it's not. Something wrong in between.
My route is:
router.post(
'/signup',
userController.validateRequest,
userController.hashPassword,
userController.signup
);
Instead of this, if I did this way:
router.post(
'/signup',
body('email').isEmail().withMessage('Please enter a valid email'),
body('password')
.equals('confirmPassword')
.withMessage('Passwords do not match'),
userController.hashPassword,
userController.signup
);
That will work But this will makes code messy if several validation requests are there.
I just want to know what is the correct way, if I separate requests and validation middleware OR do I have to pass validation in route file ONLY. Please correct me if I'm doing it the wrong way.
My validation middleware is:
exports.validateRequest = (req, res, next) => {
if (req.body.email) {
body('email').isEmail().withMessage('Please enter a valid email');
}
if (req.body.password_confirm) {
body('password')
.equals('confirmPassword')
.withMessage('Passwords do not match');
}
next();
};
And my controller where all error messages are displaying
exports.signup = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
............
Well i prefer Joi the most powerful validator
async createAccountSchema(req, res, next) {
// create schema object
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string()
.min(8)
.required(),
confirmPassword: Joi.string()
.valid(Joi.ref('password'))
.required()
.label('Passwords')
.messages({ 'any.only': '{{#label}} are not the same' }),
})
// schema options
const options = {
abortEarly: false, // include all errors
allowUnknown: true, // ignore unknown props
stripUnknown: true, // remove unknown props
}
// validate request body against schema
const result = schema.validate(req.body, options)
if (result.error) {
return res.status(400).json(result.error.details)
} else {
result.value.email = result.value.email.trim().toLowerCase()
result.value.password = result.value.password
req.body = result.value
next()
}
}
Thats an example for the validator. You pass req.body to the validator and it do the job.
After validating you set your req.body to the validation result and use next()
app.use("/", createAccountSchema, userController.signup)