Search code examples
node.jsexpressexpress-validator

Express Validator body not function


I am working to validate data input from an API call using express-validator version 6.11.1 and every time I validate using either check or body, I get the error below:

TypeError: body(...).not(...).IsEmpty is not a function

I created a helper called validator.js with the code below

const { body, validationResult } = require('express-validator')
const bcrypt = require('bcrypt')

const signupValidation = () => {
    return [
        body('firstname')
            .not().IsEmpty().withMessage('Firstname field is required'),
        body('lastname')
            .not().IsEmpty().withMessage('Lastname field is required')
    ]
}

const validate = (req, res, next) => {
    const errors = validationResult(req)
    if (errors.isEmpty()) {
        return next()
    }
    const extractedErrors = []
    errors.array().map(err => extractedErrors.push({ msg: err.msg }))

    res.status(200).json({
        statusCode: 422,
        error: extractedErrors
    })
}

module.exports = {
    signupValidation,
    validate
}

The route where I am calling it looks like

const { signupValidation, validate } = require('../../helpers/validator')

//Endpoint to create new merchant
router.post('/account/create-merchant', signupValidation(), validate, async (req, res) => {
    res.status(200).json({ 
        statusCode: 201,
        message: req.body
    })
})

Sample Data from the API

{
    "firstname": "",
    "lastname": "Jon",
    "phone" : "*****",
    "email" : "oayayayaya",
    "password": "******"
}

Can you please guide me on what to do to solve the error message (TypeError: body(...).not(...).IsEmpty is not a function)


Solution

  • I think it should be isEmpty() instead of IsEmpty(), try this:

    const signupValidation = () => {
        return [
            body('firstname')
                .not().isEmpty().withMessage('Firstname field is required'),
            body('lastname')
                .not().isEmpty().withMessage('Lastname field is required')
        ]
    }
    

    Check the doc here