I am using npm module [express-validator][1] to validate my query and body parameter. As in express , we can pass list of function as a middleware , I have created an separate file as validator. Here my code of the validator..
creditcard.validator.js
const { check, body , query ,oneOf, validationResult } = require('express-validator/check');
exports.post_credit_check = [
function(req,res,next) {
body('firstName')
.exists()
.isAlphanumeric().withMessage('firstName should be alpanumeric')
.isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
.trim();
var errorValidation = validationResult(req);
if ( errorValidation ) {
return res.status(500).json({
title: 'an error occured',
error: errorValidation
});
}
next()
},
function(req,res,next) {
body('lastName')
.exists()
.isAlphanumeric().withMessage('lastName should be alpanumeric')
.isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
.trim();
var errorValidation = validationResult(req);
if ( errorValidation ) {
return res.status(500).json({
title: 'an error occured',
error: errorValidation
});
}
next()
}
];
Here my the route file where I am passing the middleware validator array
var express = require('express');
var router = express.Router();
var Creditcard = require('../models/creditcard.model');
const { validationResult } = require('express-validator/check');
var validate = require('../models/creditcard.validate');
router.post('/creditcarddetails', validate.post_credit_check , function(req, res, next) {
.................
}
Though I am passing all middleware function in validate.post_credit_check, it not validating the body and not giving the error.