Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

103
Vistas
Problem with express-validator calling a method from controller

I'm trying to validate user data using express-validator, but when I call the user registration method in the controller from routes file, the page doesn´t load. If I extract the method to the route, it works. I want to keep it separated to keep some order in my project. Here is my routes file:

    import { Router } from "express";
    import RegisterController from '../controllers/RegisterController';
    import { body, validationResult } from "express-validator";
    import pool from '../database/db';
    import Hash from '../lib/bcrypt';
    
    const router = Router();
    
    router.get('/', (req, res) => {
        res.render('home', {
            title: 'Inicio',
        });
    });
    
    router.get('/formulario-registro', RegisterController.index);
    router.post('/register', [
    
        body('username')
            .notEmpty()
            .withMessage('El nombre de usuario no debe quedar vacío.'),
    
        body('email')
            .notEmpty()
            .withMessage('El email no debe quedar vacío')
            .isEmail()
            .withMessage('El email debe de tener un formato correcto.'),
    
        body('password')
            .notEmpty()
            .withMessage('La contraseña no debe de quedar vacía.')
            .isLength({
                min: 8
            })
            .withMessage('La contraseña debe de tener 8 caracteres como mínimo.')
            .custom((value, { req }) => {
                if (value !== req.body.confirm__password) {
                    return false;
                } else {
                    return true;
                }
            })
            .withMessage('Las contraseñas deben coincidir.')
    
    ], (req, res) => {
    
        const errors = validationResult(req);
    
        if (!errors.isEmpty()) {
            return res.status(400).json({
                errors: errors.array()
            });
        } else {
            RegisterController.register;
        }
    });
    
    router

.get('/formulario-login', (req, res) => {
    res.render('login_form', {
        title: 'Inicio de sesión'
    });
});

export default router;

Here is my controller:

import Hash from '../lib/bcrypt';
import pool from '../database/db';

class RegisterController {

    index(req, res) {
        res.render('register_form', {
            title: 'Registro'
        });
    }

    register(req, res) {

        const sql = 'INSERT INTO contact_app.users (username, email, password) VALUES (?, ?, ?)';

        pool.query(sql, [req.body.username, req.body.email, Hash.encryptPass(req.body.password)], (err) => {
            if (err) {
                console.error(err);
            } else {
                console.log('User registered correctly.');
            }
        });

        res.redirect('/formulario-login');

    }

}

export default new RegisterController;

Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

1. I think you can check your validation error in your controller and you pass your function directly to your route, this is your route file:

router.post('/register', [

    body('username')
        .notEmpty()
        .withMessage('El nombre de usuario no debe quedar vacío.'),

    body('email')
        .notEmpty()
        .withMessage('El email no debe quedar vacío')
        .isEmail()
        .withMessage('El email debe de tener un formato correcto.'),

    body('password')
        .notEmpty()
        .withMessage('La contraseña no debe de quedar vacía.')
        .isLength({
            min: 8
        })
        .withMessage('La contraseña debe de tener 8 caracteres como mínimo.')
        .custom((value, { req }) => {
            if (value !== req.body.confirm__password) {
                return false;
            } else {
                return true;
            }
        })
        .withMessage('Las contraseñas deben coincidir.')

], RegisterController.register);

and this is your controller function:

import Hash from '../lib/bcrypt'; import pool from '../database/db';

class RegisterController {

    index(req, res) {
        res.render('register_form', {
            title: 'Registro'
        });
    }

    register(req, res) {
        const errors = validationResult(req);

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

        const sql = 'INSERT INTO contact_app.users (username, email, password) VALUES (?, ?, ?)';

        pool.query(sql, [req.body.username, req.body.email, Hash.encryptPass(req.body.password)], (err) => {
            if (err) {
                console.error(err);
            } else {
                console.log('User registered correctly.');
            }
        });

        res.redirect('/formulario-login');

    }

}

export default new RegisterController;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda