validation-middleware
Flexible asynchronous validation middleware to sanitize and validate parameters at the same time. Based on validator.
Installing
npm install validation-middleware
Use
Which parameters does it receive? options, source = 'body', context = 'request'
.
First param, options
, this field is an object with the items you want to validate, e.g:
_id: 'isMongoId' date: 'required' 'isDate' // By default the parameters are not required website: required: true isUrl: params: protocols: 'https' require_host: true
The second param, source
, it will tell middleware function where to find
values to validate, by default it uses body
key, but here you can find
the same rules of the next item.
The third param, context
, it will specify an object useful if you want
to set your custom function and then have multiple options; those string values are allowed:
context
will return an object{request: ..., response: ..}
request
orresponse
, by default we userequest
- Any key in the request object.
Validators
Those are the available attributes for a validation stage.
// Dot notation is allowed 'field.name': <validation
It's flexible because there's different ways to make a validation middleware, you can define custom functions too:
email: 'required' 'isEmail' name: 'required' 'user.name': required: true // First validation stage custom: // Second validation stage { return value } params: /.*/ig ... // Other stages
This is a list with the allowed validation function names, required
validation stage is different,
if it's set to false and the value from the source is empty the next stages are skipped.
Some functions have associated sanitizers functions by default:
- isBoolean
- isDate
- isInt
- isFloat
- isMongoId
- There's other sanitize function that could be assigned
If you want to avoid this behavior you should specify it, otherwise next middleware functions will get updated values:
'product._id': required: true isMongoId: sanitize: false
Error case
You can set your own error constructor, then an instance of this will be passed to the next express middleware
{ Error thismessage = message} Object;
Example
let middleware = ; // request.body = {// user: {// uuid: '9'// },// _id: '51b14c2de8e185801f000006',// email: 'EXAMPLE@ACME.COM',// }app;
TODO
- Add support for more languages.
- en_US should have better error messages.
- See validator and add more error messages for other functions.
- Support for custom params error.
process.nextTick
is called every 3 times, it should be customizable.