Search code examples
node.jsvalidationexpressexpress-validator

express-validator Break validator chain


I am using express-validator plugin for express

var input = {
            'username': {
                notEmpty: true,
                isEmail: {
                    errorMessage: 'Invalid Email.'
                }
            },
            'password': {
                notEmpty: true,
                errorMessage: 'Invalid Password' // Error message for the parameter
            }
        };

    req.checkBody(input);
    var errors = req.validationErrors();
    if (errors) {
        console.log(errors);
    }

If I pass username as empty output is

[ { param: 'username', msg: 'Invalid param', value: '' },
  { param: 'username', msg: 'Invalid Email.', value: '' },
  { param: 'password', msg: 'Invalid Password', value: '' } ]

how to brake the chain if anyone of the validation fails.


Solution

  • The fix for this has finally landed in v3.0.0!

    req.getValidationResult().then( result => {
        var errors = result.useFirstErrorOnly().array();
        // enjoy an array with no duplicated errors for any given parameter!
    });
    

    Update: In newer versions of express-validator you can just pass an option to validationResult.array():

    var errors = validationResult(req).array({ onlyFirstError: true });