Express-validator In Node JS

Hello Everyone,

Today we will learn how to implement express-validator in Node JS

let’s start with create our project folder structure

Step 1 : Create Node JS Project

npm init  -y

Step 2 : Install following Packages

npm i express express-validator

Step 3: Create Node JS Server in app.js file

const express = require('express')
const app = express()
const userRoutes = require('./routes/user')


//routes
app.use(express.json())
app.use('/api',userRoutes)

app.listen(7676,()=>{
    console.log(`Server is Running On Port No : 7676`);
})

Step 4 :  Then after go validator folder in create user.js file add following code

const { check, validationResult } = require('express-validator');

exports.validateAddUserRequest = [
    check('firstName')
    .notEmpty()
    .withMessage('firstName is required'),
    check('lastName')
    .notEmpty()
    .withMessage('lastName is required'),
    check('lastName'),
    check('email')
    .isEmail()
    .withMessage('Valid Email is required'),
    check('password')
    .isLength({ min: 6 })
    .withMessage('Password must be at least 6 character long')
];

exports.isRequestValidated = (req, res, next) => {
    const errors = validationResult(req);
    if(errors.array().length > 0){
        return res.status(400).json({ error: errors.array()[0].msg })
    }
    next();
}

Step 5: go to router folder inside user.js file and call this above function in user routes

const { addUser } = require('../controller/user')
const { validateAddUserRequest, isRequestValidated } = require('../validator/user')

const router = require('express').Router()


router.post('/user/adduser',validateAddUserRequest,isRequestValidated, addUser)
module.exports = router

let’s test this API

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories