Search code examples
node.jsexpresspostbackendexpress-validator

express-validator doesn't check anything


Here is my code. I want to check that name is alphabetic and have more than 2 characters, but this code doesn't generate any error.

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

function nameValidation(req, res, next){
    body('name').trim().isLength({ min: 1 }).withMessage('Name empty.')
    .isLength({ min: 3 }).withMessage('Name must contain min 2 letters.')
    .isAlpha().withMessage('Name must be alphabet letters.');
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    next();
}

Solution

  • Indeed, because you did the validation after the post method gets request data. What you need to do is do the validation first.

    app.post(
        '/users',
        body('name').trim().isLength({ min: 1 }).withMessage('Name empty.')
        .isLength({ min: 3 }).withMessage('Name must contain min 2 letters.')
        .isAlpha().withMessage('Name must be alphabet letters.'),
        (req, res) => {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
              return res.status(400).json({ errors: errors.array() });
            }
            else{
                res.send('Success')
            }
        },
      );
    

    Updated

    per your comment, I update my answer to use that middleware as argument

    const express = require('express')
    const app = express()
    const port = 3000
    
    app.use(express.json())
    
    const { check, validationResult } = require('express-validator');
    
    const validateUser = [
        check('name')
            .trim()
            .escape()
            .not()
            .isEmpty()
            .withMessage('User name can not be empty!')
            .bail()
            .isLength({ min: 3 })
            .withMessage('Minimum 3 characters required!')
            .bail()
            .isAlpha()
            .withMessage('Name must be alphabet letters.')
            .bail(),
        check('email')
            .trim()
            .normalizeEmail()
            .not()
            .isEmpty()
            .withMessage('Invalid email address!')
            .bail(),
        (req, res, next) => {
            const errors = validationResult(req);
            if (!errors.isEmpty())
                return res.status(400).json({ errors: errors.array() });
            next();
        },
    ];
    
    app.get('/', (req, res) => {
        res.send('Hello World!')
    })
    
    
    app.post(
        '/users',
        validateUser,
        (req, res, next) => {
            res.send('Success')
        },
    );
    
    app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
    })