This is a nodejs file The code takes in email name and other things validates it and stores it in the database. Now as far as i know we can use app.use(expressValidator()) but here the definition has changed and its a little confusing
const express =require("express")
const bodyParser = require("body-parser")
const path = require('path')
const expressValidator = require('express-validator')
const mongojs = require('mongojs')
const db = mongojs('studentdata', ['users'])
const app = express()
const Port = 3000
//view engine
app.set('view engine','ejs')
app.set('views',path.join(__dirname,'views'))
//middleware bodyParser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))
app.use(express.static(path.join(__dirname,'public')))
app.use( (req,res,next) => {
res.locals.errors = null;
next()
})
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
const users = []
app.get('/', (req,res) => {
db.users.find( (err,docs) => {
res.render("index", {
title:'Students',
users: docs
})
})
})
app.post('/users/add', (req,res) => {
req.checkBody('first_name','First Name is Required').notEmpty()
req.checkBody('last_name','last Name is Required').notEmpty()
req.checkBody('email','email is Required').notEmpty()
req.checkBody('d_o_b','Date of birth is Required').notEmpty()
var errors = req.validationErrors()
if(errors){
res.render("index", {
title:'Students',
users: users,
errors: errors
})
}else{
var newUser = {
email : req.body.email,
first_name : req.body.first_name,
last_name : req.body.last_name,
d_o_b :req.body.d_o_b
}
db.users.insert(newUser, (err,result) => {
if(err){
console.log(err)
}
res.redirect('/')
})
}
} )
app.listen(Port, () => {
console.log('Server conned on '+Port)
})
I am confused on with this part of the code
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
I searched the internet and I was unable to understand the parameters of this expressValidators. And also is there a documentation of this expressValidator?