API validation with Sails.js

(No Ratings Yet)
Loading...

Upon many failed efforts to find a working validation hook / middleware for Sails.js 1.x, I gave up and created my own helper hook. You can find it under sails-hook-validation-ev on github.

About

It is a Sails 1.x hook for validating REST requests with the help of express-validator. Because - why reinvent the wheel? Uses the same configuration functions as express-validator. Supports validators, sanitizers, localization, …

Installation

As simple as:

$ npm install - save sails-hook-validation-ev

Usage with blueprints

For models with blueprint routes you wish to validate, you need only add a validate function to it.

Example model

Todo.js:

module.exports = {
 
  attributes: {
    title: {    
      type: 'string',   
      required: true    
    },  
     description: { 
      type: 'string',   
      required: true    
    },
  },
 
  validate: (req) => {
    req.check('title')
      .exists()
      .isLength({ min: 1 }).withMessage('must be at least 5 chars long');
    req.check('description').exists();
  }
 
};

For info on which functions you can use, see express-validator check API. It opens a world of possibilities 🙂

Example POST /todo response

    {
        "errors": [
            {
                "location": "params",
                "param": "title",
                "msg": "Invalid value"
            },
            {
                "location": "params",
                "param": "title",
                "msg": "must be at least 5 chars long"
            }
        ]
    }

Usage with custom handlers

The following snippets will override default /POST blueprint handler with custom function. In overridden functions you hold the responsibility to validate requests.

Option 1: Validate via validate function in model

With this option you should provide a validate function inside your model as illustrated in the example Todo.js above.

TodoController.js:

var validate = require('sails-hook-validation-ev/lib/validate')
 
module.exports = {
  create: async function(req, res) {
    validate(req)
    const errors = await req.getValidationResult();
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    return res.ok()
  }  
};

Option 2: Provide a custom validate function

This option enables you to validate routes like login, register, …

TodoController.js:

var validate = require('sails-hook-validation-ev/lib/validate')
 
module.exports = {
  create: async function(req, res) {
    validate(req, (req) => {
      req.check('title')
        .exists()
        .isLength({ min: 1 }).withMessage('must be at least 5 chars long');
      req.check('description').exists();
    })
 
    const errors = await req.getValidationResult();
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    return res.ok()
  }  
};

Your email is kept private. Required fields are marked *