title: Passport.js local login with body validation and error handling
body: <p>I need body validation and better error handling without the first validation middleware. The code works very well, but I would like to delete the first middleware and manage validation within the second.</p>
  
  <p><strong>routes/auth.js</strong></p>
  
  <pre><code>router.post('/signin', function(req, res, next){
  
      req.checkBody('email', 'Email is required.').notEmpty();
      req.checkBody('email', 'Invalid email format.').isEmail();
      req.checkBody('password', 'Password is required.').notEmpty();
      req.checkBody('password', 'The password length must be between 8 and 100.').isLength({min: 8, max: 100});
  
      var err = req.validationErrors();
      if (err) {
          res.status(400).send({ success: false, error: err});
          return;
      }
      next();
  });
  
  router.post('/signin', passport.authenticate('local', { session: false }), function(req, res){
      var user = req.user;
      return res.json({success: true, user: user});
  });
  </code></pre>
  
  <p>As regards the error handling, if a user doesn't match, the error is:</p>
  
  <pre><code>{
    "error": "Invalid email and/or password"
  }
  </code></pre>
  
  <p>and I would like this:</p>
  
  <pre><code>{
    "success":false,
    "error": "Invalid email and/or password"
  }
  </code></pre>
  
  <p>How can I do it?</p>
  
  <p><strong>passport.js</strong></p>
  
  <pre><code>passport.use(new LocalStrategy({
          usernameField: 'email',
          passwordField: 'password'
      },
      function(email, password, done) {
          User.findOne({ email: email, password: password },'-password', function (err, user) {
              if (err)return done(err);
              if(!user){
                  var err = new Error('Invalid email and/or password');
                  err.status = 401;
                  return done(err, false);
              }
  
              return done(null, user);
          })
      }
  ));
  </code></pre>
  
  <p>Thanks for the replies.</p>