I'm trying to build a route middleware function to validate a form, but I got a little confused about how should I get errors.
How is validationErrors populated and how should I access it inside route function? The examples I found at the docs and other sites did not helped me
route:
use strict';
const express = require('express');
const router = express.Router();
const User = require('../back/api/models/UserModel');
const Helper = require('./handlerInputs.js');
const bcrypt = require('bcrypt');
router.post('/registrar', [Helper.validaRegistro], function (req, res, next) {
const errors = validationResult(req).throw();
if (errors) {
return res.status(422).json({ errors: errors });
}
[... user register code .... ]
});
handler:
'use strict'
const { check, validationResults } = require('express-validator');
exports.validaRegistro = function(req, res, next){
check(req.body.nome)
.not().isEmpty()
.withMessage('Nome é obrigatório')
.isLength({min: 3, max: 20})
.withMessage('Nome deve ter entre 3 e 20 caracteres')
.isAlpha('Nome deve ser literal');
check(req.body.email)
.normalizeEmail()
.isEmail()
.withMessage('Email inválido');
optPwd = {
checkNull: false,
checkFalsy: false
}
check(req.body.password)
.exists(optPwd)
.withMessage('Senha é obrigatória');
check(req.body.password === req.body.passordconf)
.exists()
.withMessage('Confirme a senha')
.custom((value, { req }) => value === req.body.password)
.withMessage('Senhas não são iguais')
.custom((value, { req }) => value.length >= 8)
const result = req.getValidationResults();
const erros = req.ValidationErrors;
if(erros){
console.log(erros);
}
????
}
What you can do is, Just write validation logic inside middleware itself rather than writing the same thing again and again on the different controller.
Another best way to create common logic is to put validation rules on different files and put handling validation logic in a different file. Please follow this URL, I have implemented the same thing with efficient way.
https://github.com/narayansharma91/node_quick_start_with_knex
if(erros){
const status = 422;
res.status(status).json({
success: false,
status,
errors: errors.array(),
});
}