validator-param
A library, which can create validators to validate request parameters easily.
Install
npm install validator-param --save
How to use
The basic usage
const expect = ;const Validator = ; const schema = requiredParam : required: true 'The requiredParam can not be empty'//when check failed return a Error object ;const validator = schema;const error = validator;tobe; const schema2 = jsonParam : required:true//when check failed return a inner error string type:JSONcode:1msg:'The jsonParam must be a JSON object'//when check failed return a custom object ;const validator2 = schema2;const error2 = validator2;tobeandhaveand;
code 2.1.1 The basic usage
Use as express middleware
This is a directory tree of our web project:
│─app.js
│
├─bin
│ www
│
├─public
│ ├─images
│ ├─javascripts
│ └─stylesheets
│ style.css
│
├─routes
│ index.js
│
├─validators
│ data_list_schema.js
│
└─views
error.ejs
index.ejs
directory tree
And then it is the code of app.js , where we introduce the middleware supplied by request-param:
const express = ;const path = ;const logger = ;const bodyParser = ;const filter:requestValidator = ;const index = ; const app = ; app;app; app;app;app;app;app;
code 2.2.1 The code of app.js
As showed above, the files in directory of validators
with a suffix of _schema.js
will be parsed. And we have the file data_list_schema.js
in it, so the url of /i/data/list
will be validate by the definition of the file data_list_schema.js
. For the parameter urlPrefix
is /i/
, the paramter filenameReplaces
is {'_':'/'}
, the filename will be remove the filenameSuffix
and replace filenameReplaces
's key with its value, and unshfited with urlPrefix
.
moduleexports = Object;
code 2.2.2 The code of data_list_schema.js
As showed in code 2.2.2, when request /i/data/list
without parameter begin_time
or in wrong type(not a Date), the middleware will return a error object.
API
See the api document.
Attention
Not use querysting in POST method, it will case the req.query's data type transform fail.