13

I'm trying to install and use express-validator package. I've installed the package version (6.0.0) and then in my server.js file the code is:

const bodyParser = require('body-parser')
const expressValidator = require('express-validator')
const express = require('express')
const nunjucks = require('nunjucks')
const sessionInMemory = require('express-session')
const cookieParser = require('cookie-parser')

Then a few lines down I've put in the following:

const app = express()
const documentationApp = express()
app.use(expressValidator())

When the server reloads the changes (using nodemon) the app crashes and says:

TypeError: expressValidator is not a function

There are other bits of code in my server.js file but I've stripped out most of it that isn't relevant I think.

Console log for expressValidator:

{ oneOf: [Function: oneOf],
  buildSanitizeFunction: [Function: buildSanitizeFunction],
  sanitize: [Function],
  sanitizeBody: [Function],
  sanitizeCookie: [Function],
  sanitizeParam: [Function],
  sanitizeQuery: [Function],
  buildCheckFunction: [Function: buildCheckFunction],
  check: [Function],
  body: [Function],
  cookie: [Function],
  header: [Function],
  param: [Function],
  query: [Function],
  checkSchema: [Function: checkSchema],
  matchedData: [Function: matchedData],
  validationResult: { [Function] withDefaults: [Function: withDefaults] },
  Result: [Function: Result] }

Code for routes.js file:

router.get('/email-adress', function (req, res) {
  res.render('email-adress', { success: req.session.success, errors: req.session.errors })
  req.session.errors = null
})

router.post('/finished', function (req, res) {
  let email = req.body.email

  req.checkBody('email', 'Email required').isEmail()

  var errors = req.validationErrors()
  if (errors) {
    req.session.errors = errors
    req.session.success = false
    res.redirect('/email-adress')
  } else {
    req.session.success = true
    res.redirect('/finished')
  }
})
Michael Gearon
  • 445
  • 1
  • 4
  • 16
  • console log your expressValidator and show the result – Radonirina Maminiaina Jun 24 '19 at 09:50
  • check the docs https://express-validator.github.io/docs/6.0.0/ its different than what you're doing here it's requiring const { check, validationResult } = require('express-validator'); then passing checks as middleware in the route [ check('username').isEmail(), check('password').isLength({ min: 5 }) ] – arpitansu Jun 24 '19 at 09:52
  • expressValidator is an object not a function. ;) – Radonirina Maminiaina Jun 24 '19 at 09:55
  • @ArpitPandey I can see the difference there, I've just added the code for routes.js file, that checks the email input to make sure it's a valid email address. I'm not sure how I would rewrite that code for version 6? – Michael Gearon Jun 24 '19 at 10:22

8 Answers8

28

Express Validator has been updated therefore, you can't use it this way This is a new way to use the express validator

Weather stick with the previous version or use the current syntex of it.

npm uninstall express-validator
npm install express-validator@5.3.0
MD SHAYON
  • 7,001
  • 45
  • 38
7

Yeah! Even I had the same problem. You can change the version by writing the command in root folder.

Command:

npm install express-validator@5.3.1 --save-exact
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
vamshi mannem
  • 125
  • 1
  • 2
4
//just pass the checking as middleware not in the callback
//see here I've just passed an array for checking as middleware
// as the middleware is an array therefore you can add multiple checks in the array
router.post("/", [check('email', "your custom error message").isEmail()], (req, res) => {

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
   res.render('errorPage', { errors: errors.array() });
   //if api caller return res.status(422).json({ errors: errors.array() });
  }
  else{
    //here everything is ok to proceed
   res.render('successPage', { data });
   //to api caller  res.json({msg : "ok"})
  }

})
arpitansu
  • 588
  • 4
  • 12
  • That’s pretty much working, thank you. Just one final question, now it’s returning the JSON how would I go about putting the JSON into a template and render either the email-address page if there is an error or if it’s fine then render the finished page? Thanks for your help – Michael Gearon Jun 24 '19 at 10:59
  • you can just use the res.render in the if else conditions if your view is in the API or just return the JSON to the API caller if your view is separate and decide there what you want to show. – arpitansu Jun 24 '19 at 11:17
  • check i've made changes – arpitansu Jun 24 '19 at 11:25
  • Got that working, the final problem is that it's showing the errorPage but with the URL of the success (finished page). I'm guessing it needs some logic in the if errors.isEmpty go/stay on the original page rather than going to the post page? – Michael Gearon Jun 24 '19 at 12:58
  • Then just use the red.redirect feature of the express it will redirect to the successUrl or errorUrl as per your needs, just check this thread https://stackoverflow.com/questions/19035373/how-do-i-redirect-in-expressjs-while-passing-some-context – arpitansu Jun 24 '19 at 13:37
  • Solved, what I done in the end was set the post to the same page where you input the email address. Then if successful redirect to the finished page. Thanks for your help. – Michael Gearon Jun 24 '19 at 14:39
2
const { check, validationResult } = require('express-validator');
router.post('/finished', function (req, res) {
let email = req.body.email

check('email', 'Email required').isEmail()

var errors = validationResult(req)
if (errors) {
  req.session.errors = errors
  req.session.success = false
  res.redirect('/email-adress')
  } else {
  req.session.success = true
  res.redirect('/finished')
  }
})

Do this. And remove

app.use(expressValidator()) 

line.

2

Go to package.json change "express-validator": "^6.6.0" to "express-validator": "^5.3.0", manually then run npm i

Jude Okagu
  • 195
  • 2
  • 6
  • The question is using the version 6.0.0 of the library. It could be useful to understand the answer to explain why to downgrade the version of the library and why to do it manually. Can it be solved in the same library version as the answer says? – piraces Jul 07 '20 at 21:44
  • I wonder if you even run the solution at all before giving a negative rating...this easily solves the problem regardless just like other posts above best to stop looking for pointless excuses to give negative rating. – Jude Okagu Jul 08 '20 at 16:32
1
just update the express validator , will do the tri

npm install express-validator@5.3.1 --save-exact

0

This happened to me because I was following an outdated (2019) tutorial. It works if you install an older version (5.3.1 worked for me). I ran into this working along with the book "Get Programming with Node.js" by Jonathan Wexler.

-5
app.use(expressValidator());

Replace this line with

app.use(expressValidator);