Skip to content

Commit b8d706a

Browse files
committed
ReadMe changes
1 parent 2228f9a commit b8d706a

File tree

7 files changed

+454
-123
lines changed

7 files changed

+454
-123
lines changed

.npmignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@
1010
/lib/skipService/skipService.test.js
1111
_config.yml
1212
.eslintrc.js
13-
sonar-project.properties
13+
sonar-project.properties
14+
README@2.3.0.md

README.md

Lines changed: 195 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -45,49 +45,58 @@ $ npm install expressjs-field-validator
4545
## How To Use
4646

4747
```js
48-
const { validator } = require('expressjs-field-validator');
48+
const {
49+
validateBody,
50+
validateParam,
51+
validateQuery,
52+
param,
53+
} = require('expressjs-field-validator');
4954
```
5055
```js
51-
router.get('/users/:id',
52-
validator([{param : 'id', location : 'params', isRequired : true}], { mode : 'reject', errorCode : '422' }),
56+
router.post('/users/:id',
57+
validateParam().addParams([
58+
param('id').isNumber().end()
59+
]).done(),
60+
validateBody().addParams([
61+
param('userId').isNumber().end()
62+
]).done(),
63+
validateQuery().addParams([
64+
param('userName').isRequired().end()
65+
]).done(),
66+
validateHeader().addParams([
67+
param('Authorization').isRequired().end()
68+
]).done(),
5369
(req, res, next) => {
5470

5571
// Main Service Here
5672

5773
});
5874
```
59-
## validator arguments
60-
61-
| Argument | Type | Description
62-
|:---------------|:---------:|----------------------------|
63-
|validator |`Object[]` | Array of validation object |
64-
|Response |`Object` | This Object determines the proceeding to the next step |
65-
66-
### validator Object
67-
68-
69-
| Property | Type | Description
70-
|:---------------|:---------|----------------------------|
71-
|param |`String` | Field name|
72-
|location |`String` | Location of the field (`body`/`params`/`query`) only mandatory for higher order objects (direclty under `body`/`params`/`query`) default `body` |
73-
|children |`Object[]` |Array of Child validator objects, only applicable if the field is `Array` or `Object` |
74-
|isArray |`Boolean` |The value is `Array` or not (default `false`)|
75-
|isObject |`Boolean` |The value is `Object` or not (default `false`)|
76-
|isRequired |`Boolean` |The value is mandatory or not (default `false`)|
77-
|isNumber |`Boolean` |The value is `Number` or not (default `false`)|
78-
|range |`Object` |Object `{min : 1, max : 10}` describes minimum and maximum value of a Number field|
79-
|isEmail |`Boolean` |The value is `Email` or not (default `false`)|
80-
|isBoolean |`Boolean` |The value is `Boolean` or not (default `false`)|
81-
|isDate |`Boolean` |The value is `Date` or not (default `false`)|
82-
|format |`String` |Date format. (default `YYYY-MM-DD`)|
83-
|mobileNumber |`Object` |Object `{countryCode : '91', isCountryCodeMandatory : true, length: {min : 1, max : 10}}` ,describes characteristics of mobile number, length is the length range of mobile number excluding country code |
84-
|length |`Object` |Object `{min : 1, max : 10}` describes minimum and maximum length|
85-
|includes |`Object[]` |Value must be one of the element in the array|
86-
|excludes |`Object[]` |Value must not be one of the element in the array|
87-
|message |`String` |Error message thrown in case of test fails default : Invalid Field Error|
88-
89-
#### Supported date formats
90-
If `isDate` is true you can pass `format`, Only supported the following
75+
## Getting Started
76+
### Defining a Field
77+
Use `param(<field Name>)` to define a field. It should end with `end()`
78+
```js
79+
param('userName').isRequired().end()
80+
```
81+
Defines a field `userName` which is mandatory.
82+
#### Available Options
83+
##### isRequired()
84+
Field is mandatory
85+
##### isArray()
86+
Expects array
87+
##### isObject()
88+
Expects object
89+
##### isNumber()
90+
Expects number
91+
##### isEmail()
92+
Expects email
93+
##### isBoolean()
94+
Expects boolean value
95+
##### isDate()
96+
Expects a date with default format `YYYY-MM-DD`
97+
##### dateFormat(format)
98+
* `format` *Mandatory* String
99+
specify date format, supported
91100
```
92101
YYYY-MM-DD
93102
DD-MM-YYYY'
@@ -96,96 +105,115 @@ YYYY/MM/DD'
96105
DD/MM/YYYY'
97106
MM/DD/YYYY'
98107
```
99-
#### Nested Objets
100-
In case of `Object` or `Array`, `isArray` or `isObject` must be true
101-
if json structure is
108+
##### minimumNumber(min)
109+
* `min` *Mandatory* Number
110+
Expects number and must be greater than or equal to `min`
111+
##### maximumNumber(max)
112+
* `max` *Mandatory* Number
113+
Expects number and must be less than or equal to `max`
114+
##### minimumLength(min)
115+
* `min` *Mandatory* Number
116+
Expects number/string and length must be less than or equal to `min`
117+
##### maximumLength(max)
118+
* `max` *Mandatory* Number
119+
Expects number/string and length must be less than or equal to `max`
120+
##### shouldInclude(inclues)
121+
* `inclues` *Mandatory* Array
122+
Expects number/string and must be one of given array `includes`
123+
##### shouldExclude(excludes)
124+
* `excludes` *Mandatory* Array
125+
Expects number/string and must not be one of given array `excludes`
126+
##### isMobileNumberWithCountryCode(countryCode)
127+
* `countryCode` *Mandatory* String
128+
Expects mobile number with or without `countryCode`
129+
##### isMobileNumberWithCountryCodeMandatory()
130+
Expects mobile number which should starts with country code set at `isMobileNumberWithCountryCode`
131+
##### isMobileNumberWithMinimumLength(min)
132+
* `min` *Mandatory* Number
133+
Minimum length of mobile number without country code
134+
##### isMobileNumberWithMaximumLength(max)
135+
* `max` *Mandatory* Number
136+
Maximum length of mobile number without country code
137+
##### addChild(child)
138+
* `child` *Mandatory* field definition object
139+
Add a child object for arrays and objects
140+
##### addChildren(children)
141+
* `children` *Mandatory* Array of field definition objects
142+
Add a list of children objects for arrays and objects
143+
##### sendErrorMessage(message)
144+
* `message` *Mandatory* String
145+
Custom message to be send back in case of validation failure
102146
```js
147+
// Default message
103148
{
104-
"page" : {
105-
"sorted" : "True"
106-
},
107-
"sort" : [{
108-
"value" : [{
109-
"date" : "2019-01-01",
110-
"length" : {"min" : "1", "max" : "100"}
111-
}]
112-
}]
149+
"error": [
150+
{
151+
"location": "body.sort",
152+
"param": "sort",
153+
"message": "Invalid Field Error"
154+
}
155+
]
113156
}
114-
```
115-
the validator object
116-
```js
117-
[
118-
{param : 'page', location : 'body', isObject : true, children : [
119-
{param : 'sorted', location : 'body.page', isRequired : true, isBoolean : true, message='Mandatory field page missing'},
120-
]},
121-
{param : 'sort', location : 'body', isArray : true, children : [
122-
{param : 'value', location : 'body.sort', isArray : true, children : [
123-
{param : 'date', location : 'body.sort.value', isRequired : true, isDate : true},
124-
{param : 'length', location : 'body.sort.value', isObject : true, children : [
125-
{param : 'min', location : 'body.sort.value.length', isNumber : true},
126-
{param : 'max', location : 'body.sort.value.length', isNumber : true}
127-
]}
128-
]}
129-
]}
130-
]
131-
```
132-
### Response object
133-
134-
| Property | Type | Description
135-
|:---------------|:---------|----------------------------|
136-
|mode |`String` | can be `reject` or `forward`, Mandatory field|
137-
|errorCode |`String` | Error code send in response. default `422` Error|
138-
|debug |`Boolean` | set `true` to respond back more details on error |
139-
140-
#### Mode
141-
Value can be can be `reject` or `forward`.
142-
##### Reject
143-
Response is sent back with http status code provided in `errorCode` property
144-
```js
157+
// Custom message
145158
{
146159
"error": [
147160
{
148161
"location": "body.sort",
149162
"param": "sort",
150-
"message": "Invalid Field Error"
163+
"message": "<Your Custom Error Message>"
151164
}
152165
]
153166
}
154167
```
155-
##### Forward
156-
Error is set to `request.locals.data` and error code to `request.locals.statusCode`. Forward the request to next middleware.
168+
##### end() :bangbang::bangbang: Mandatory
169+
Ends a param definition
157170

158-
#### debug
159-
If `debug` is set to `true`, error response will be
171+
### Creating a validation middleware
172+
* `validateBody()` *Validate body*
173+
* `validateParam()` *Validate param*
174+
* `validateQuery()` *Validate query*
175+
* `validateHeader()` *Validate header*
176+
177+
#### Available Options
178+
##### isToBeRejected()
179+
Defines the validation failure event - Server returns http status code set via `sendErrorCode` (default 422), :heavy_exclamation_mark: will not proceed to the next middleware
180+
Response body
160181
```js
161182
{
162183
"error": [
163184
{
164185
"location": "body.sort",
165186
"param": "sort",
166-
"message": "Invalid Field Error :: somevalueforsort Must Be A Boolean"
187+
"message": "Invalid Field Error"
167188
}
168189
]
169190
}
170191
```
171-
It will give more idea about the error.
172-
173-
## checkService
192+
##### isToBeForwarded()
193+
Defines the validation failure event - Error is set to `request.locals.data` and error code to `request.locals.statusCode`, :white_check_mark: will proceed to the next middleware
194+
Error object
195+
Response body
174196
```js
175-
const { checkService } = require('expressjs-field-validator');
197+
{
198+
"error": [
199+
{
200+
"location": "body.sort",
201+
"param": "sort",
202+
"message": "Invalid Field Error"
203+
}
204+
]
205+
}
176206
```
177-
178-
It helps to skip the main service function, if you have used forward mode.
179-
### Usage
180-
Pass your service function to `checkService`, which must be skipped.
207+
###### checkService
181208
```js
182-
checkService((req, resp, next) => {
183-
184-
})
209+
const { checkService } = require('expressjs-field-validator');
185210
```
211+
Pass middleware to `checkService`, which must be skipped if `isToBeForwarded` enabled and validation errors are found
186212
```js
187213
router.get('/users/:id',
188-
validator([{param : 'id', location : 'params', isRequired : true, isNumber: true}], { mode : 'forward' }),
214+
validateBody().isToBeForwarded().sendErrorCode(500).debug(false).addParams([
215+
param('id').isRequired().isNumber().end()
216+
]).done(),
189217
checkService((req, res, next) => {
190218

191219
// This middleware is skipped if id is empty or not a number
@@ -197,34 +225,82 @@ checkService((req, res, next) => {
197225

198226
});
199227
```
200-
201-
## skipService
228+
###### skipService
229+
manually invoke forward mode, if this is set from any middleware, the middlewares wrapped inside `checkService` won't be executed
202230
```js
203231
const { skipService } = require('expressjs-field-validator');
204-
205-
skipService(req, 'SOME-ERROR');
206232
```
207-
### Arguments
208-
| Property | Type | Description
209-
|:---------------|:---------|----------------------------|
210-
|req |`Object` | Pass the request object|
211-
|statusCode |`String` | Some status code to identify the error. Read the data from `request.locals.statusCode` |
233+
```js
234+
router.get('/users/:id',
235+
(req, res, next) => {
236+
237+
skipService(req, 'SOME-ERROR');
238+
next();
239+
240+
}),
241+
242+
checkService((req, res, next) => {
243+
244+
// This middleware is skipped
245+
246+
}),
247+
(req, res, next) => {
212248

213-
It helps to skip the main service function manually.
214-
### Usage
215-
Pass your service function to `checkService`, which must be skipped. Use `skipService` in the middleware which is added before the main service
249+
// This middleware Will not be skipped, error data will be availble here - req.locals.data and status code - request.locals.statusCode here
250+
251+
});
252+
```
253+
##### sendErrorCode(errorCode)
254+
* `errorCode` *Mandatory* Error code which should be rejected
255+
##### debug(isDebugEnabled)
256+
* `isDebugEnabled` *Mandatory* Pass `true` for development environments, the error object will contain more details about error
257+
Error object
216258
```js
217-
[
218-
(req, resp, next) => {
219-
skipService(req, 'SOME-ERROR');
220-
next();
221-
},
222-
checkService((req, resp, next) => {
223-
// This will be skipped
224-
}),
225-
(req, resp, next) => {
226-
// This will not be skipped
259+
{
260+
"error": [
261+
{
262+
"location": "body.sort",
263+
"param": "sort",
264+
"message": "Invalid Field Error :: somevalueforsort Must Be A Boolean" // More details on error
265+
}
266+
]
267+
}
268+
```
269+
##### addParams(paramList)
270+
* `paramList` *Mandatory* Array of field definition objects
271+
##### done() :bangbang::bangbang: Mandatory
272+
Ends a validation definition
273+
## Dealing with nested objects
274+
### Request body
275+
```js
276+
{
277+
"field1": "Value", // String, Mandatory
278+
"field2": [ // array, Mandatory
279+
{ "field21": "44443" } // Number Optional
280+
]
281+
"field3": { // Object Optional
282+
{ "field31": "true" } // Boolean Mandatory
283+
{ "field32": "String" } // String Mandatory
227284
}
228-
]
285+
}
229286
```
287+
Should send http status code 500 in case of error
288+
### Validation
289+
```js
290+
router.post('/users/:id',
291+
validateBody().isToBeRejected().sendErrorCode(500).addParams([
292+
param('field1').isRequired().end(),
293+
param('field2').isRequired().isArray().isRequired().addChild(
294+
param('field21').isNumber().end()
295+
).end(),
296+
param('field3').isRequired().isObject().addChildren([
297+
param('field31').isBoolean().isRequired().end(),
298+
param('field32').isRequired().end()
299+
]).end(),
300+
]).done(),
301+
(req, res, next) => {
230302

303+
// Main Service Here
304+
305+
});
306+
```

0 commit comments

Comments
 (0)