This sails-hook-req-validate package uses req.allParams() (Sails Document).
FYI, sails' req.allParams() returns the value of all parameters sent in the request which includes querystring and url path. Which means passing parameters may be string type, use converter to convert the type to an expected value type. But please note that some validation types have build-in converters, check validation type list for more information.
For example: /api/user/:age/:ismale or /api/user?age=12&ismale=true. req.allParams() returns all parameters as string, however sails-hook-req-validate can correctly validate the type and convert to the correct output type in most cases.
Installation
``javascript npm install sails-hook-req-validate --save ` This is it! Once you npm install the hook will be automatically activated. However, if you want more control, see below for the config/validate.js setting.
Report Bug & Suggest Improvement
Please feel free to leave any comment and suggestion . https://github.com/JohnKimDev/sails-hook-req-validate/issues/new
--- ---
Optional Global Setting (config/validate.js)
You can create a config/validate.js file in TWO different ways. Please note that the local, (req.validate() configuration) can overwrite the global configuration.
OPTION 1: Simple Object Notation (no response & request objects will be passed)
`javascript /** * Sails-Hook-Req-Validate Global Configuration * * For more information on the settings in this file, see: * https://github.com/JohnKimDev/sails-hook-req-validate/blob/master/readme.md **/
module.exports.validate = { /* * When validation error occurs, the program can send theres.badRequest * response automatically. * * By Default,
sendResponse is enabled. */ // sendResponse: true,
/* * After the validation check, the program returns data as object or you * can use a callback. But it can return the data as a PROMISE if you set *
usePromise as true. * * By Default, usePromise is disabled. */ // usePromise: false,
/* * When there are more incoming request parameters than listed in the *
req.validate option, by default, it will return all incoming parameters * If you disable returnAllParams option, it will filter parameters and only * return the parameters that are listed in the req.validate validate option * * By Default, returnAllParams is enabled. */ // returnAllParams: true,
/* * Error output format * errMessage : ((string)) short explanation of a reason for the invalidation * invalidKeys : ((array))[string] list of invalid parameter key(s) * * Output can be any format you want. The return value from
onErrorOutput * will be passed to the final error return. */ // onErrorOutput: function (errMessage, invalidKeys) { // return { message: errMessage, invalid: invalidKeys }; // },
/* * Required error message output * keys : ((string)) or ((array))[string] one or more list of invalid * parameter key(s) * * [output] ((string)) */ // requiredErrorMessage: function(keys) { // keys = keys || []; // let isare = (keys.length > 1) ? 'are' : 'is'; // let s = (keys.length > 1) ? 's' : '' // return
The "${keys.join('", "')}" parameter${s} ${isare} required.; // },
validationTypes.js * https://github.com/JohnKimDev/sails-hook-req-validate/blob/master/lib/validationTypes.js * * [output] ((string)) */ // inputErrorMessage: function(key, typeMessage) { // let a = (typeMessage && typeMessage.length) ? /[aeiouAEIOU]/.test(typeMessage.charAt(0)) ? 'an' : 'a' : ''; // return The "${key}" parameter has an invalid input type + (typeMessage ? , it should be ${a} ${typeMessage} : '') + '.'; // },
/* * Incoming request parameter invalid error message output of OR validation * example: 'string|number
* orKey : ((string)) invalid parameter key * orTypeMessages: ((string)) combined types[key].message from validationTypes.js * https://github.com/JohnKimDev/sails-hook-req-validate/blob/master/lib/validationTypes.js * * [output] ((string)) */ // orInputErrorMessage: function(orKey, orTypeMessages) { // return Invalid input type, it should be one of the following types; ${orTypeMessages}.; // } }; ``
OPTION 2: Function return (response & request objects will be passed)
`javascript /** * Sails-Hook-Req-Validate Global Configuration * * For more information on the settings in this file, see: * https://github.com/JohnKimDev/sails-hook-req-validate/blob/master/readme.md * * The response and request objects will be passed to the configuration function when initializes **/
module.exports.validate = function(req, res) { return { /* * When
sendResponse is enabled. The program will use this responseMethod * to send the error data out. By default, it will use res.badRequest. * The res object is from the passing parameter with is a response object * from the controller. * * You can overwrite the responseMethod with another response function or * create your own response handler. * example: * responseMethod: (data) => { * sails.log.error(data); * res.set(400).send(data); * } */ // responseMethod: res.badRequest
/** * You can use all other configurations from the OPTION 1 example **/ }; };
`
---
USAGE - Validator
sails-hook-req-validate is very flexible and can be used in many different formats and configurations.
--- New in 2.8.x
Function Validation
`javascript const params = req.validate({ 'evenNum': (val) => { return (val % 2 === 0); } // you can also use a function instead of an arrow function });
// PRO TIP: (val) => { return (val % 2 === 0); } can be shorten to (val) => (val % 2 === 0)
`
---
Single parameter
`javascript const params = req.validate('id'); ` Multiple parameters `javascript const params = req.validate(['id', 'firstname', 'lastname']); ` Simple validator `javascript const params = req.validate({ 'id': 'base64|number|boolean' // OR operation 'name': ['string', 'email'], // AND operation 'email?': 'email', // OPTIONAL parameter 'zipcode': 'postalcode' }); ` Combined validators `javascript const params = req.validate({ 'name': ['string', { default: 'John Doe' }], // default value if missing 'email?': ['email', { converter: 'normalizeEmail' }], // optional parameter & with converter 'type': { enum: ['user', 'admin', 'manager'], default: 'user' } }); ` Combined validators as array `javascript const params = req.validate([ { 'name': ['string', { default: 'John Doe' }] }, // default value if missing { 'email?': ['email', { converter: 'normalizeEmail' }] }, // optional parameter & with converter { 'type': { enum: ['user', 'admin', 'manager'], default: 'user' } } ]); ` Multiple converters `javascript const params = req.validate({ 'email': ['any', { converter: ['string', 'normalizeEmail'] }] }); // not a good example but I hope you get the idea `
Option | Description --------------------------------------- | -------------------------------------- enum | ((array)) any combination of expected values default | ((string\|number\|boolean)) default value if the parameter is missing converter | ((array\|function)) converter name as string or array of string can be used. You can pass
function for custom converter. You can also mixed types + functions in an array. validator | ((function)) if you need a custom validator, use this option