Search code examples
node.jsexpressexpress-handlebarsexpress-validator

How to console.log individual req.checkBody params(errors msg) - express-Validator


This code working fine. It throws errors and displayed to the webpage. But now i want to pick individual errors and display to the webpage.

    // request.body validation
  req.checkBody('email', 'Email is required.').notEmpty();
  req.checkBody('name', 'Name is required.').notEmpty();
  req.checkBody('phone', 'Phone is required.').isMobilePhone('en-IN');
  req.checkBody('password1', 'Password is required.').isLength({min:6});
  req.checkBody('password2', 'Password not same, try again!!').equals(password1);

  var errors = req.validationErrors();

  if (errors) {
    console.log(req.body.params.errors);
    res.render('form', {
      errors: errors,
      isForm: true,
      register: true
    });
  } else {
    console.log('PASSED');
  }

What will be the code to console.log individual params of the errors?


Solution

  • The easiest way is to turn on mapped. That makes the errors array an ordinary object, so you can access the particular errors with dot syntax:

      var errors = req.validationErrors(true);  // note the true argument
    
      if (errors) {
        console.log(errors);
    
        res.render('form', {
          errors: errors.phone,  // ordinary object access syntax
          isForm: true,
          register: true
        });
      } else {
        console.log('PASSED');
      }
    

    You can also do it with mapped set to false. This is the default way.

    The errors variable is then an array, so you can access its elements like in any other array:

      if (errors) {
        res.render('form', {
          errors: errors[0], // only the first error
          isForm: true,
          register: true
        });
      } else {
        console.log('PASSED');
      }
    

    If you want to send an element that belongs to a particular field you can use a for loop to find its location in errors:

      // request.body validation
      req.checkBody('email', 'Email is required.').notEmpty();
      req.checkBody('name', 'Name is required.').notEmpty();
      req.checkBody('phone', 'Phone is required.').isMobilePhone('en-IN');
      req.checkBody('password1', 'Password is required.').isLength({ min: 6 });
      req.checkBody('password2', 'Password not same, try again!!').equals('password1');
    
      var errors = req.validationErrors();
    
      if (errors) {
        // look for phone
        let indexOfPhone = -1;
        for (let i = 0; i < errors.length; i += 1) {
          if (errors[i].param === 'phone') indexOfPhone = i;
        }
    
        res.render('form', {
          errors: errors[indexOfPhone],
          isForm: true,
          register: true
        });
      } else {
        console.log('PASSED');
      }