express validator custom error not working

484 Views Asked by At

I am using express-validator to validate input, also using Sequelize ORM for database queries. Trying to validate a custom function on express-validator. The function is always failing, no matter the output Here is the validator body

Validator:

body('firmName').notEmpty().withMessage('Firm Name is required.').custom((name, { req, loc, path }) => {
    Firm.findOne({ where: { firmName: name }}).then(firm => {
        if(firm != null) {
            return Promise.reject('errr')
        } else {
            return Promise.resolve('Ok')
        }
    }).catch(err => {
        console.log(err)
        return Promise.reject('errr')
    })
}).withMessage('Firm Name already exists.'),

This is how i am sending result out from my controller:

const errors = validationResult(req);
 if (!errors.isEmpty()) {
 return res.status(422).json({ errors: errors.array() });
}

The Sequelize is working fine but validation always fails. I tried returning boolean but those also fails.

1

There are 1 best solutions below

0
On

console.log the errors.array() and see what are these failures and fix them.

if (!errors.isEmpty()) {
 console.log(errors.array());
 return res.status(422).json({ errors: errors.array() });
}