Here is my code. I want to check that name is alphabetic and have more than 2 characters, but this code doesn't generate any error.
const {body, validationResult} = require('express-validator');
function nameValidation(req, res, next){
body('name').trim().isLength({ min: 1 }).withMessage('Name empty.')
.isLength({ min: 3 }).withMessage('Name must contain min 2 letters.')
.isAlpha().withMessage('Name must be alphabet letters.');
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
}
CodePudding user response:
Indeed, because you did the validation after the post method gets request data. What you need to do is do the validation first.
app.post(
'/users',
body('name').trim().isLength({ min: 1 }).withMessage('Name empty.')
.isLength({ min: 3 }).withMessage('Name must contain min 2 letters.')
.isAlpha().withMessage('Name must be alphabet letters.'),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
else{
res.send('Success')
}
},
);
Updated
per your comment, I update my answer to use that middleware as argument
const express = require('express')
const app = express()
const port = 3000
app.use(express.json())
const { check, validationResult } = require('express-validator');
const validateUser = [
check('name')
.trim()
.escape()
.not()
.isEmpty()
.withMessage('User name can not be empty!')
.bail()
.isLength({ min: 3 })
.withMessage('Minimum 3 characters required!')
.bail()
.isAlpha()
.withMessage('Name must be alphabet letters.')
.bail(),
check('email')
.trim()
.normalizeEmail()
.not()
.isEmpty()
.withMessage('Invalid email address!')
.bail(),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty())
return res.status(400).json({ errors: errors.array() });
next();
},
];
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post(
'/users',
validateUser,
(req, res, next) => {
res.send('Success')
},
);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
CodePudding user response:
With the help of first answer I find the correct solution for my case, here it is:
const express = require('express')
const router = express.Router()
const {body, validationResult} = require('express-validator');
const nameValidation =
body('name').trim().isLength({ min: 1 }).withMessage('Name empty.')
.isLength({ min: 3 }).withMessage('Name must contain min 3 letters.')
.isAlpha().withMessage('Name must be alphabet letters.');
router.post('/new', nameValidation, poneNumberValidation, (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array()});
}
const contact = req.body;
contact.id = getRandomId();
contacts.push(contact);
res.redirect("/contacts");
res.render("index", {contacts});
})
PS: poneNumberValidation and getRandomId are functions that I implemented in my code, they are not related to this question.