Search code examples
expressexpress-validator

express-validator few custom validations check


I need to check if user with passed email OR login already exists in database.

const userModel = new User();
const user = await userModel.findByLogin(req.body.email, req.body.login);

if (user) {
  req.checkBody('email', 'Email already in use').custom(value => user.email === value ? Promise.reject('Email already in use') : value);
  req.checkBody('login', 'Login already in use').custom(value => user.login === value ? Promise.reject('Login already in use') : value);
}

const errors = req.validationErrors();

findByLogin takes email and login and returns existing user or null. Email validation works as expected. But if I try to register user with unique email and existing login, it doesn't create any errors (errors is false).


Solution

  • I just messed up with asynchronous validation. I cannot use validationErrors in my case, so I changed it to getValidationResult and it works fine now. Here is the result:

    const userModel = new User();
    const user = await userModel.findByLogin(req.body.email, req.body.login)
    if (user) {
      req.checkBody('email', 'Email already in use').custom(value => user.email !== value ? value : Promise.reject('Email already in use')).withMessage('Email already in use');
      req.checkBody('login', 'Login already in use').custom(value => user.login !== value ? value : Promise.reject('Login already in use'));
    }
    
    const errors = await req.getValidationResult();