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, ...
As simple as npm install --save sails-hook-validation-ev
.
For models with blueprint routes you wish to validate, you need only add a validate
function to it.
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 :)
{
"errors": [
{
"location": "params",
"param": "title",
"msg": "Invalid value"
},
{
"location": "params",
"param": "title",
"msg": "must be at least 5 chars long"
}
]
}
The following snippet will override default /POST blueprint handler with custom function. In overridden functions you hold the responsibility to validate requests.
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()
}
};
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()
}
};