How to add Joi params, query, body validation to Sails JS?

Let’s keep the things short. I am working on a SailsJS app and I am missing a lot the HapiJS Joi validation features. It keeps the validation logic separate and isolated from the controllers and other stuff. So I was wondering how to integrate Joi with Sails.

Sails has the concept of policies. A policy is a function that receives request and response, executes some code and either prevents the request from continuing or calls the next() function so the request can propagate to the other policies. A policy is a simple js file placed in the policies folder of the project and registered in the config/policies.js file of your project. I made a small project on Github to illustrate that – HERE.

I made a modelValidation.js policy which is registered in the config/policies.js file for the AuthController.login which is a POST method – you can verify it in the config/routes.js file. Here is what the policy does:

function modelValidation(req, res, next) {
  // get the req.options.validation property and try to load a file
  // from the api/validaton directory with the property name
  var schema = require('../validation/' + req.options.validation)
  if (!schema) {
    return res.serverErrorJson(new Error("Missing validation schema for " + req.options.controller + " " + req.options.action))
  }

  // Here body can also be used with params, query etc.
  Joi.validate(req.body, schema.body, function (err, value) {
    if (err != null) {
      error = err.details[0]
      error.statusCode = 400
      return res.badRequest({ error: error }, req.options.action);
    } else {
      return next();
    }
  })
};

Shortly speaking. It takes the property of req.options.validation. It can be seen in the routes.js file. The validation property is “login”. So it will look for the following file api/validation/login.js.

It will validate then the request body against the schema.body declared in the login.js file, which is a Joi validation schema and based on that will either continue or return bad request to the client. Here is the required schema, it requires the password to contain only numbers. Using this same approach you can validate the params or the query of the body. You just have to add some additional validation logic.

So this is the whole concept of using Joi with Sails. If you have any questions ask me here or write me an email. And don’t forget to check the GITHUB example.

One thought on “How to add Joi params, query, body validation to Sails JS?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s