Search code examples
validationexpressexpress-validator

getting req.getValidationResult is not a function with expess validator


I use the latest express-validator and I keep getting req.getValidationResult is not a function even though every example has this syntax.

In my routes I have

const express = require('express');
const router = express.Router();
const signup = require('../lib/signup.js');
const {body, validationResult } = require('express-validator/check');
router.post('/submit',
[
  body('username').not().isEmpty().withMessage('please enter username'),
  body('password').not().isEmpty().withMessage('please enter password')
],
(req, res)=>{
  req.getValidationResult().then( result => {
    var errors = result.array(); 
    console.log('errors', errors);
  })
}

I dont have anything express-validator-related in my app.js. In my package.json I have "express-validator": "*", in the dependencies.

If I do

  let errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log('errors ', errors);
  }

it works.

I dont know why I keep getting req.getValidationResult is not a function . I dont have a clue what is going on. Please advice. Thanks


Solution

  • express-validator maintainer here.

    Starting with express-validator v4.0.0, all methods accessible from the req object are considered legacy and are going to be deprecated soon.
    This means any methods like req.checkBody, req.validationResult, req.sanitize, etc, shouldn't be used for new applications.

    Using methods from any of the other APIs of express-validator (but the legacy one) is preferred.
    validationResult(req) is the correct way to access the validation errors, and it returns the exact same object as req.getValidationResult(), but in a synchronous way.

    * Please note that since express-validator has changed a lot lately, I recommend against following tutorials published before August 2017.