DEV Community

loading...

Discussion on: A Clean Approach to Using Express Validator

Collapse
nedsoft profile image
Chinedu Orie Author

You can use a custom rule

See example from the docs:

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

app.post('/user', body('passwordConfirmation').custom((value, { req }) => {
  if (value !== req.body.password) {
    throw new Error('Password confirmation does not match password');
  }

  // Indicates the success of this synchronous custom validator
  return true;
}), (req, res) => {
  // Handle the request
});
Collapse
damien1990 profile image
Damien1990

Thank you, it worked beautifully. I'm guessing you can use a similar approach to checking for 'unique' emails/usernames by requiring the model in the validator class, using the value to search for existing emails/usernames in the database and if one is returned, to throw an error?

Thread Thread
nedsoft profile image