Search code examples
express-validator

express-validator throwing error with valid field


Did my best to follow the docs here, but I can't get this to work.

server.js

const express = require('express');
const app = express();
app.use(express.json())
app.use('/', index);

index.js

const router = express.Router()
const { check, validationResult } = require('express-validator/check')

router.post('/register', [
  check('name').exists()
  ], function(req, res) {
  const validationErrors = validationResult(req)
  if (!validationErrors.isEmpty()) {
    console.log("validationErrors.array()\n", validationErrors.array())
  }
})

To test this, I am entering a valid name in the client, and it shows up just fine in req.body. Might be worth noting that req.body has the following structure:

{ userRegistrationForm:
   { name: 'John Doe',
     email: 'john@example.com',
     password: '',
     gender: '',
     birthMonth: 'Month',
     birthDate: 'Day',
     birthYear: 'Year' } }

The docs mention check('username').isEmail(),, but I don't know where 'username' is coming from, unless the check() method is looking at req.body by default.

No matter what I do (meaning I enter a valid name), I keep getting the same validation error:

[ { location: 'body',
    param: 'name',
    value: undefined,
    msg: 'Invalid value' } ]

How do I correctly use the check() method?

Update:

I think I figured it out. I modified my client to pass req.body.name to the server (as opposed to req.body.userRegistrationForm.name), and check('name') seems to catch the error when I omit a name. Still, I'd like to get feedback on this issue.


Solution

  • express-validator maintainer here.

    In order to select fields that are nested within other objects, you specify its path using dot notation*:

    check('userRegistrationForm.name')
    

    * I acknowledge that if you're asking, we may need better docs to cover this! PRs welcome.