Reputation: 87
I'm using express-validator.
I want to generate an error in validationResult if the field is empty.
This is my code:
router.post('/register',[
check('name').isEmpty().withMessage('Name field cannot be empty.'),
check('email').isEmail().withMessage('Enter valid email address.'),
check('username').isEmpty().withMessage('Username cannot be empty.'),
check('password').isEmpty().matches('password2').withMessage('Password dont match.')
], function(req, res, next) {
const errors = validationResult(req);
console.log(errors.array());
if (!errors.isEmpty()) {
res.render('register2',{
errors: errors.mapped(),
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password,
password2: req.body.password2
});
}
});
I want to generate error when name field and username field is empty but I only get errors for these fields:
[ { location: 'body',
param: 'email',
value: '',
msg: 'Enter valid email address.' },
{ location: 'body',
param: 'password',
value: '',
msg: 'Password dont match.' } ]
Upvotes: 0
Views: 2009
Reputation: 18939
You are currently doing opposite of what you want. When you do this:
check('username').isEmpty().withMessage('Username cannot be empty.'),
you want the username to be empty and are issuing an error if it's not. You can change it to:
check('username').not().isEmpty().withMessage('Username cannot be empty.'),
or:
check('username').exists().withMessage('Username cannot be empty.'),
instead.
Upvotes: 2