Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
Express - Validation express-validator does not show errors

I'm sure this is not a problem instead I'm not using it the right way.

I want to validate user request body and according to documentation, all work is done in the route file. And I divided my work into routes and controllers files. I passed a validation middleware and it needs to be validated but it's not. Something wrong in between.

My route is:

router.post(
  '/signup',
  userController.validateRequest,
  userController.hashPassword,
  userController.signup
);

Instead of this, if I did this way:

router.post(
  '/signup',
  body('email').isEmail().withMessage('Please enter a valid email'),
  body('password')
      .equals('confirmPassword')
      .withMessage('Passwords do not match'), 
  userController.hashPassword,
  userController.signup
);

That will work But this will makes code messy if several validation requests are there.

I just want to know what is the correct way, if I separate requests and validation middleware OR do I have to pass validation in route file ONLY. Please correct me if I'm doing it the wrong way.

My validation middleware is:

exports.validateRequest = (req, res, next) => {
  if (req.body.email) {
    body('email').isEmail().withMessage('Please enter a valid email');
  }

  if (req.body.password_confirm) {
    body('password')
      .equals('confirmPassword')
      .withMessage('Passwords do not match');
  }
  next();
};

And my controller where all error messages are displaying

exports.signup = async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  ............
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Well i prefer Joi the most powerful validator

async createAccountSchema(req, res, next) {
    // create schema object
    const schema = Joi.object({
      email: Joi.string().email().required(),

      password: Joi.string()
        .min(8)
        .required(),
      confirmPassword: Joi.string()
        .valid(Joi.ref('password'))
        .required()
        .label('Passwords')
        .messages({ 'any.only': '{{#label}} are not the same' }),
    })

    // schema options
    const options = {
      abortEarly: false, // include all errors
      allowUnknown: true, // ignore unknown props
      stripUnknown: true, // remove unknown props
    }

    // validate request body against schema

    const result = schema.validate(req.body, options)

    if (result.error) {
      return res.status(400).json(result.error.details)
    } else {
      result.value.email = result.value.email.trim().toLowerCase()
      result.value.password = result.value.password
      req.body = result.value
      next()
    }
  }

Thats an example for the validator. You pass req.body to the validator and it do the job.

After validating you set your req.body to the validation result and use next()

app.use("/", createAccountSchema, userController.signup)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda