@touch4it/sails-hook-validator
v2.4.0
Published
Validation hook for Sails.js requests
Downloads
37
Readme
Sails.js request validation hook
Sails hook for validate request.
npm install --save @touch4it/sails-hook-validator
req.validator(rules, [sendResponse=true, [cb]])
Requirements:
rules
Rules defined as string parameter name (required string value) or object (more complex validation). Rules passed as array of strings or objects
Optional parameters prefixed with ?
Possible options specified later in "Validation types" section
req.validator(['name']);
req.validator([{'name': 'string'}]);
req.validator(['?name']);
sendResponse
true
: If something goes wrong, return a 400 to the user with the error
false
: Return
cb
Callback function
Return value
If something goes wrong it returns a 400 or false, based on sendResponse
. If validation is successful, it returns the params. It works as a filter too, since it returns only parameters specified in rules
.
Examples
Filter of parameters
If there is single parameter to be validated, we can pass it as string instead of array
// req.params.all() === {name: 'joseba', surname: 'legarreta'}
const params = req.validator('name');
// params === {name: 'joseba'}
For more that one params the required params have to pass it as an Array
Missing parameter causes system to return 400 if second parameter (sendResponse
) is not set or true
. False is returned if second parameter is false
// req.params.all() === {id: 1, name: 'joseba'}
const params = req.validator(['id', 'password'], false);
// params === false
if (!params) {
return null;
}
// req.params.all() === {id: 1, name: 'joseba'}
const params = req.validator(['id', 'password']);
// Sent 400 with message "password is required."
Callback function can be used to notify execution end
const filter = [
'id',
'?name',
{'?surname': ['string', 'toUpper']},
height: 'float',
'?age': 'int'
];
req.validator(filter, false, function(err, params) {
// err === {message: 'parsedError...', invalidParameters: ['invalid', 'parameter', 'list']}
if (err) {
return res.badRequest(err.message);
}
return res.ok(params);
});
or
const filter = [
'id',
'?name',
{'?surname': ['string', 'toUpper']},
height: 'float',
'?age': 'int'
];
req.validator(filter, function(err, params) {
// If error occurs the validator will use req.status(400).send(...)
return res.ok(params);
});
Apart from validation, we can also use sanitization of inputs
// req.params.all() === {id: 1, likes: '12.20', url: 'HttP://GOOGLE.eS', email: '[email protected]'}
const params = req.validator(['id', {likes: 'int', url: ['url', 'toLower'], email: 'email'}]);
// params = {id: 1, likes: 12, url: 'http://google.es', email: '[email protected]'}
// req.params.all() === {id: 1, likes: '12.20', url: 'http://google.es', email: '[email protected]'}
const params = req.validator(['id', 'url', {likes: 'float', email: 'email'}]);
// params = {id: 1, likes: 12.20, url: 'http://google.es', email: '[email protected]'}
// req.params.all() === {id: 1, likes: 'hello', url: 'http://google.es', email: '[email protected]'}
const params = req.validator(['id', {url: ['url', 'lower'], likes: 'float', email: 'email'}]);
// Client gets a 400 - 'likes' has to be a float
We can also specify optional values by prefixing ?
// If we have a nickname and/or a name parameters it will return it to the `param` applying the rules
// If nickname or/and name are undefined in the request, it will ignore them and won't send 400
const param = req.validator('?nickname', {color: ['hexcolor', 'upper'], '?name': 'toUpper'});
Validation
Validation uses validator package under the hood
Validation types
alpha
- letters onlyalphanumeric
- letters and numbersascii
base64
boolean
country2
- ISO 3166-1 alpha-2country3
- ISO 3166-1 alpha-3creditCard
date
- ISO 8601 or RFC 3339 dateemail
empty
float
fqdn
- fully qualified domain namehex
hexColor
int
ip
- IPv4 or IPv6ipRange
- IPv4 rangeisbn
- ISBNissn
- ISSNisin
- ISINisrc
- ISRCjson
jwt
latlon
lower
- lowercasemacAddress
mobilePhone
md5
mongoId
numeric
port
string
upper
- uppercaseuuid
- UUID v 3, 4 or 5url
Sanitization types
escape
- replace <, >, &, ', " and / with HTML entitiesunescape
- replaces HTML encoded entities with <, >, &, ', " and /trim
- trim whitespaces from left and rightltrim
- trim whitespaces from leftrtrim
- trim whitespaces from righttoBoolean
toDate
toEmail
toLower
toUpper
Tests
To test this hook, you need mocha installed in your computer globally.
// Just if you don't have mocha installed yet
npm install -g mocha
// And then just run mocha in the hook folder
mocha
// Optional: Change port or log level
log=info port=1234 mocha
// log level options = error, warn, info, verbose and silly. By default: warn
// port by default: 1992