i am trying to validate request body and path params in post and delete routes respectively
this is my body validation rules :-
const { body, validationResult } = require('express-validator');
const requestBodyValidationRules = [
body('originalUrl')
.not()
.isEmpty()
.withMessage({
error: 'Invalid Request Body',
detail: {
originalUrl: 'Request Syntax Error! originalUrl parameter is required',
},
}),
body('originalUrl')
.isURL({
protocols: ['http', 'https', 'ftp'],
require_protocol: true,
})
.withMessage({
error: 'Invalid Request Body',
detail: {
originalUrl: 'Invalid URL format, please try again!',
},
}),
body('convertedUrlId')
.optional({ checkFalsy: true })
.matches(/^[~A-Za-z0-9/./_/-]*$/)
.withMessage({
error: 'Invalid characters',
detail: {
convertedUrlId:
'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
},
}),
body('convertedUrlId')
.optional({ checkFalsy: true })
.isLength({ min: 5, max: 6 })
.withMessage({
error: 'Invalid length',
detail: {
convertedUrlId:
'Invalid Length! Character length >=5 and <7 characters are allowed',
},
}),
(req, res, next) => {
const errors = validationResult(req);
console.log('errors', errors);
if (!errors.isEmpty()) {
const errorMsg = errors.array()[0].msg;
return res.status(400).json(errorMsg);
}
next();
},
];
module.exports = requestBodyValidationRules;
this is my param validation rules
const { param, validationResult } = require('express-validator');
const requestParamValidationRules = [
param('convertedUrlId')
.isLength({ min: 5, max: 6 })
.withMessage({
error: 'Invalid length',
detail: {
convertedUrlId:
'Invalid Length! Character length >=5 and <7 characters are allowed',
},
}),
param('convertedUrlId')
.matches(/^[~A-Za-z0-9/./_/-]*$/)
.withMessage({
error: 'Invalid characters',
detail: {
convertedUrlId:
'Invalid characters! Only [A-Z],[a-z],[0-9], _ , - , . , ~ are allowed',
},
}),
(req, res, next) => {
const errors = validationResult(req);
console.log('errors', errors);
if (!errors.isEmpty()) {
const errorMsg = errors.array()[0].msg;
return res.status(400).json(errorMsg);
}
next();
},
];
module.exports = requestParamValidationRules;
this my app.js
app.get(
'/api-docs',
swaggerUI.serve,
swaggerUI.setup(swaggerJsDocs, swaggerOptions)
);
app.get('/:shortUrl', redirectUrlRouter);
app.post(
'/users/anon-user/urls',
checkRequestBodyParams,
fetchTimeStamp,
convertAnonUrlRouter
);
app.post(
'/users/auth-user/urls',
checkRequestBodyParams,
fetchTimeStamp,
convertAuthUrlRouter
);
app.get('/users/auth-user/urls', fetchAuthUserHistoryRouter);
app.patch('/users/auth-user/urls', fetchTimeStamp, editConvertedUrlRouter);
app.delete(
'/users/auth-user/urls/:convertedUrlId',
checkPathParams,
deleteConvertedUrlRouter
);
app.use((req, res) => {
res.status(404).json({ error: 'route not found' });
});
when ever i am trying to post
, delete validations are running, why is that so?
Desired behaviour :- for post, request body validations should be running