Express validator in controller

Hello. I use express validator in nodejs and am having a validation problem. While I was validating directly through the routes, the validation was working, however, when I implemented controllers in my system, I was not sure how to validate, because in all the ways I tried went wrong. I am using version 6 of express validator.

This is my controller

const { check, validationResult } = require('express-validator');
module.exports.formulario_inclusao_noticia = function(app, req, res){
    res.render("admin/form_add_noticia", {validacao: {}, noticia : {}});
}

module.exports.noticia_salvar = function(app, req, res){
    check('titulo').isLength({ min: 5 }).withMessage('O título deve ter no mínimo 5 letras')
    var noticia = req.body;
    const errors = validationResult(req);
    console.log(errors);
    if (!errors.isEmpty()) {
        return res.render('admin/form_add_noticia', { validacao: errors.array(), noticia : noticia});
        return;
    }
    var connection = app.config.dbConnection();
    var noticiasModel = new app.app.models.noticiasModel(connection);

    noticiasModel.salvarNoticia(noticia, function(error, result){
        res.redirect("/noticias");
    });
}

The Route:

module.exports = function(app){
    app.get('/formulario_inclusao_noticia', function(req, res){
        app.app.controllers.admin.formulario_inclusao_noticia(app, req, res);
    });
    app.post('/noticias/salvar', function(req, res){
            app.app.controllers.admin.noticia_salvar(app, req, res);
    });
}

A view:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8"/>
    <title>Formuláio de cadastro de Notícia</title>
</head>
<body>

    <h1>Adicionar notícia</h1>
    <br>
    <% if(validacao) { %>
    <ul>
        <% for(var i = 0; i < validacao.length; i++) { %>
        <li>
            <%= validacao[i].msg %>
        </li>
        <% } %>
    </ul>
    <% } %>

    <form action="/noticias/salvar" method="post">
        <label>Titulo</label>
        <input type="text" id="titulo" name="titulo" value="<%=noticia.titulo%>" placeholder="Titulo da noticia">
        <br>
        <label>Resumo</label>
        <textarea name="resumo" id="resumo" cols="30" rows="5"><%=noticia.resumo%></textarea>
        <br>
        <label>Autor</label>
        <input type="text" id="autor" name="autor" value="<%=noticia.autor%>" placeholder="Autor da noticia">
        <br>
        <label>Data dos fatos</label>
        <input type="date" id="data_noticia" name="data_noticia" value="<%=noticia.data_noticia%>" placeholder="Data da noticia">
        <br>
        <label>Noticia</label>
        <textarea name="noticia" id="noticia" cols="30" rows="5"><%=noticia.noticia%></textarea>
        <br>
        <input type="submit" value="Enviar">
    </form>

</body>
</html>

How can I do for this validation work properly?

Author: Raphael Cordeiro, 2019-08-25

1 answers

Follows excerpt from the code of how I decided to use the validator in the Controller:

Your Route file should look like this:

const { registerUser } = require('../controllers/UserController');

router.post('/signup', registerUser.validations, registerUser.handler);

And your controller should look like this:

module.exports = {
  registerUser: {
    validations: [
        // Sua validação aqui
    ],

    handler: async (req, res) => {
        // Seu código aqui
    },
  },
};

 0
Author: lmarzochi, 2020-01-30 01:25:54