Skip to content

Instantly share code, notes, and snippets.

@sgnl
Last active August 29, 2015 14:23
Show Gist options
  • Save sgnl/b64d9b589878fe04663c to your computer and use it in GitHub Desktop.
Save sgnl/b64d9b589878fe04663c to your computer and use it in GitHub Desktop.
Express Middleware Exercise - Validation

Express Middleware Exercise - Validation

Your job is to add validations to the messages being posted to your Chatroom Application's Server by implementing Middleware.

Each validation requirement below will be it's own middleware in the series.

Commit your code each time you successfully implement a new middleware handler.

Validation Requirements

Payload

req.body.message must be defined before continuing. If not defined, respond with a 422 status code and an String which describes what went wrong.

Name

  • Type: String
  • Format: Alphanumeric
  • Minimum Length: 3
  • Maximum Length: 16
  • Required: Yes
  • Additional requirements: Must not have leading or trailing spaces. Name cannot contain spaces (Alphanumeric only).

If Validation fails, respond with a 422 status code and an String which describes what went wrong.

Message

  • Type: String
  • Format: Any
  • Minimum Length: 12
  • Maximum Length: None
  • Required: Yes
  • Additional requirements: Must not have leading or trailing spaces.

If Validation fails, respond with a 422 status code and an String which describes what went wrong.

Middleware Example

router.get('/route', firstRouteHandler, secondRouteHandler);
  
function firstRouteHandler(req, res, next) {
    // continue handling this request 
    next('route');
  }
}

function secondRouteHandler(req, res, next) {
  if(err) {
    return next(err);
  }
  res.json({message: "Success"});
}

References

Middleware

Error Handling

// in your server.js file, below your routes
app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

400 vs 422 Status Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment