Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!