Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No errors with express-validator isEmpty

I am using express-validator 5.2.0 in a expressjs app. I implemented the validaiton on a form data. But it does not capture the errors and gives empty errors object. When validation runs it shows the "no error" when I submit the empty form. It should follow the error path and should display the error.

var express = require('express');
var router = express.Router();
const { check, validationResult } = require('express-validator/check');

router.post('/register', [
  check('firstName', 'First Name is required').isEmpty(),
  check('lastName', 'Last Name is required').isEmpty(),
  check('username', 'User Name is required').isEmpty(),
  check('password', 'Password is required').isEmpty()
], (req, res, next)=>{
  let errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log(errors.mapped());
    console.log("errors")
    return res.render('auth/register', { errors: errors.mapped() })
  }else{
    console.log('no errors')
    return res.render('auth/login');
  }
like image 809
Arun kumar Avatar asked Jun 08 '18 20:06

Arun kumar


People also ask

What is not () in Express validator?

notEmpty() adds a validator to check if a value is not empty; that is, a string with a length of 1 or bigger. https://express-validator.github.io/docs/validation-chain-api.html#notempty. Follow this answer to receive notifications.

What is validationResult in Express validator?

validationResult(req) Extracts the validation errors from a request and makes them available in a Result object. Each error returned by . array() and . mapped() methods has the following format by default: { "msg": "The error message", "param": "param.

What is checkFalsy in Express validator?

checkFalsy: if true, fields with falsy values (eg "", 0, false, null) will also be considered optional.

What is bail in Express validation?

According to the express-validator documentation: . bail() is useful to prevent a custom validator that touches a database or external API from running when you know it will fail. Can be used multiple times IN THE SAME validation chain if needed.


1 Answers

check('firstName', 'First Name is required').isEmpty() is enforcing firstName to be empty.
You will want to change that last part to .not().isEmpty(), so that you invert the isEmpty validator.

Might also be of your interest: https://github.com/express-validator/express-validator/issues/476

like image 171
gustavohenke Avatar answered Oct 03 '22 23:10

gustavohenke