0
Hello. I use the Validator express in the nodejs and I’m having a validation problem. When I was validating directly through the routes, the validation was working, however, when I implemented controllers on my system, I was left without knowing how to validate, because in all the ways I tried to go wrong. I’m 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);
});
}
The 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 make this validation work properly?