validator-chain
Version:
Powerful tool for validate input parameters in the most stylish way. Could be use as simple test case in conditional statement or in standalone chain of validation
574 lines (361 loc) • 17.3 kB
Markdown
# Module Validator
## Usage
### With throw try catch
```javascript
const Validator = require('validator-chain');
function some(p1, p2, p3, error) {
Validator(p1, 'p1').must.exist().must.be.number().and.not.equal(0).is.lowerThan(256).try();
Validator(p2, 'p2').exist().string().not.length(0).match(/^[A-Z]{4}$/).try();
Validator(p3, 'p3').array().not.have.length(6).each((vChild) => {
vChild.object().keys('address', 'zipcode', 'email', 'age', (vAddress, vZipcode, vEmail, vAge) => {
vAddress.string(); // Don't call try/resolve on nested chain
vZipcode.string().match(/^[0-9]{4}$/);
vEmail.string().match(...);
vAge.number();
}); // Don't call try/resolve on nested chain
}).try();
// And so on ...
}
```
### With resolve then catch
```javascript
const Validator = require('validator-chain');
function idChain(vId) {
vId.integer().not.equal(0)
}
function some(customer) {
return Validator(customer, 'customer').or(
idChain,
vCustomer => vCustomer.object().keys(
{ key: 'id', chain: idChain },
{ key: 'name', chain: (vName => vName.string().length(vLength => vlength.greaterThan(3).not.greaterThan(20)).match(/^[\w-']$/)) },
{ key: 'email', chain: vEmail => vEmail.string().match(/^[\w]+@[\w]+\.[\w]{2,}$/) },
{ key: 'age', optional: true, chain: vAge => vAge.integer().greaterThan(0).not.greaterThan(130) },
),
).resolve().then(() => {
}).catch((error) => {
});
}
```
<!-- ```javascript
``` -->
### Express/Koa control body
```javascript
app.put('/api/catalog/mine/products/:id',
Validator.mw.express.body({ key: 'label', chain: vLabel => vLabel.string() }),
Validator.mw.express.body({ key: 'enabled', optional: true, chain: vEnabled => vEnabled.boolean() }),
Validator.mw.express.body({ key: 'quantity', optional: true, chain: vQuantity => vQuantity.or(vQ => vQ.equal(null), vQ => vQ.integer()) }),
Validator.mw.express.body({ key: 'price', optional: true, chain: vPrice => vPrice.integer().greaterThan(0) }),
Validator.mw.express.body({ key: 'reference', optional: true, chain: v => v.or(vRef => vRef.equal(null), vRef => vRef.string()) }),
(req, res) => {
// TODO
});
```
## References
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
#### Table of Contents
- [callbacks](#callbacks)
- [ErrorBuilder](#errorbuilder)
- [Checker](#checker)
- [Parameters](#parameters)
- [ChainApplier](#chainapplier)
- [Parameters](#parameters-1)
- [instanceOf](#instanceof)
- [Parameters](#parameters-2)
- [isInstance](#isinstance)
- [Parameters](#parameters-3)
- [mustBeInstance](#mustbeinstance)
- [Parameters](#parameters-4)
- [Validator](#validator)
- [isValid](#isvalid)
- [error](#error)
- [invalidate](#invalidate)
- [Parameters](#parameters-5)
- [invalidateOn](#invalidateon)
- [Parameters](#parameters-6)
- [setModifier](#setmodifier)
- [Parameters](#parameters-7)
- [resetModifier](#resetmodifier)
- [not](#not)
- [apply](#apply)
- [Parameters](#parameters-8)
- [exist](#exist)
- [type](#type)
- [Parameters](#parameters-9)
- [instance](#instance)
- [Parameters](#parameters-10)
- [equal](#equal)
- [Parameters](#parameters-11)
- [among](#among)
- [Parameters](#parameters-12)
- [greaterThan](#greaterthan)
- [Parameters](#parameters-13)
- [lowerThan](#lowerthan)
- [Parameters](#parameters-14)
- [greaterOrEqualThan](#greaterorequalthan)
- [Parameters](#parameters-15)
- [lowerOrEqualThan](#lowerorequalthan)
- [Parameters](#parameters-16)
- [match](#match)
- [Parameters](#parameters-17)
- [startsWith](#startswith)
- [Parameters](#parameters-18)
- [endsWith](#endswith)
- [Parameters](#parameters-19)
- [hexadecimal](#hexadecimal)
- [base64](#base64)
- [url](#url)
- [boolean](#boolean)
- [number](#number)
- [integer](#integer)
- [string](#string)
- [object](#object)
- [array](#array)
- [function](#function)
- [length](#length)
- [Parameters](#parameters-20)
- [each](#each)
- [Parameters](#parameters-21)
- [keys](#keys)
- [Parameters](#parameters-22)
- [or](#or)
- [Parameters](#parameters-23)
- [try](#try)
- [resolve](#resolve)
### callbacks
#### ErrorBuilder
Function building error.
Returns **[Error](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error)** Responsible error.
#### Checker
Function checking if "value" is valid or not
##### Parameters
- `value` **any** Value to check.
Returns **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if valid, false otherwise.
#### ChainApplier
Function appling chain validation on parameter.
##### Parameters
- `Validator` **[Validator](#validator)** to apply chain on.
### instanceOf
Access 'constructor.name'.<br/>
if undefined or null, return 'undefined'
#### Parameters
- `data` **any** argument
Returns **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Type name, one of 'undefined', 'Boolean', 'Number', 'String', 'Array', 'Object', 'Function', '${ClassName}'
### isInstance
- **See: [instanceOf](#instanceof)**
Compare if item is an element of expectedType. Allow inheritance.
#### Parameters
- `item` **any** Element for which type is checked.
- `expectedInstance` **([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function))** String representation or constructor of type to looking for
Returns **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if item or its ancestry is type of expectedType.
### mustBeInstance
Compare if item is an element of expectedType. Allow inheritance.<br/>
Throw error if failed.
#### Parameters
- `item` **any** Element for which type is checked.
- `expectedInstance` **([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function))** String representation or constructor of type to looking for
- `name` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Name of item for error building
Returns **[undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined)**
### Validator
#### isValid
Return if chain is valid or invalidated
Returns **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if valid, false otherwise
#### error
returns the error responsible for the invalidation
Returns **Errors** Responsible error or null.
#### invalidate
Invalidate chain with given responsible error
##### Parameters
- `error` **Errors** Responsible error.
Returns **[Validator](#validator)** this for chaining.
#### invalidateOn
Invalidate depending on test return
##### Parameters
- `check` **Checker** Function returning boolean
- `buildError` **ErrorBuilder** Function returning error in case of failure. Used if test succeed au modifie is true.
- `buildRevError` **ErrorBuilder** Function returning error in case of failure. Used if test failed and modifier is false. (optional, default `buildError`)
Returns **[Validator](#validator)** this for chaining.
#### setModifier
Change modifier state. true for normal validation, false for reverse validation.
##### Parameters
- `modifier` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Boolean value for modifier.
Returns **[Validator](#validator)** this for chaining.
#### resetModifier
Set modifier back to true (normal validation).
Returns **[Validator](#validator)** this for chaining.
#### not
Reverse modifier
Returns **[Validator](#validator)** this for chaining.
#### apply
Execute "chain" with this validator.
##### Parameters
- `chain` **ChainApplier** Function appling chain validation.
Returns **[Validator](#validator)** this for chaining.
#### exist
- **See: [instanceOf](#instanceof)**
Validate that value exists excluding undefined and null.
Returns **[Validator](#validator)** this for chaining.
#### type
Validate that value type is equal to expectedType. According to typeof.
##### Parameters
- `expectedType` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Type description string ('undefined', 'boolean', 'number', 'string', 'object').
Returns **[Validator](#validator)** this for chaining.
#### instance
- **See: [isInstance](#isinstance)**
- **See: [or](or)**
Validate that value instance is equals to expectedInstance. According to isInstance.
##### Parameters
- `expectedType` **([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function))** Type description string ('Boolean', 'Number', 'String', 'Object', Object, Error, ...).
Returns **[Validator](#validator)** this for chaining.
#### equal
- **See: [lodash#isEqual](https://lodash.com/docs/4.17.15#isEqual)**
Validate that value is equal to parameter according to lodash#isEqual
##### Parameters
- `value` **any** Value to compare with.
Returns **[Validator](#validator)** this for chaining.
#### among
Validate that value is included in parameter values.
##### Parameters
- `values` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<any>** Values to look through.
Returns **[Validator](#validator)** this for chaining.
#### greaterThan
Validate that value is greater than limit parameter (excluded).<br/>
Use reverse function not.lowerThan to include limit.
##### Parameters
- `limit` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** Limit parameter.
Returns **[Validator](#validator)** this for chaining.
#### lowerThan
Validate that value is lower than limit parameter (excluded).<br/>
Use reverse function not.greaterThan to include limit.
##### Parameters
- `limit` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** Limit parameter.
Returns **[Validator](#validator)** this for chaining.
#### greaterOrEqualThan
Shortcut for not.lowerThan(limit)
##### Parameters
- `limit` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** Limit parameter.
Returns **[Validator](#validator)** this for chaining.
#### lowerOrEqualThan
Shortcut for not.greaterThan(limit)
##### Parameters
- `limit` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** Limit parameter.
Returns **[Validator](#validator)** this for chaining.
#### match
Validate that value match given regexp
##### Parameters
- `regex` **[RegExp](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp)** RegExp to validate.
Returns **[Validator](#validator)** this for chaining.
#### startsWith
- **See: [String#startsWith](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/startsWith)**
Validate that value startsWith given sub string.
##### Parameters
- `needle` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Sub string to look for.
Returns **[Validator](#validator)** this for chaining.
#### endsWith
- **See: [String#endsWith](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/endsWith)**
Validate that value endsWith given sub string.
##### Parameters
- `needle` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Sub string to look for.
Returns **[Validator](#validator)** this for chaining.
#### hexadecimal
Validate that value contains hexadecimal character only and it's length is even.<br/>
Shortcut for match(/^([0-9a-fA-F]{2})\*$/).
Returns **[Validator](#validator)** this for chaining.
#### base64
Validate that value contains base64 character only and it's length is valid for base64.<br/>
Shortcut for match(/^([A-Za-z0-9+/]{4})\*([A-Za-z0-9+/]{2,3}==?)?$/).
Returns **[Validator](#validator)** this for chaining.
#### url
Validate that value is an url.<br/>
Used RegExp ^(<http://www.|https://www.|http://|https://>)?[a-z0-9]+([-.]{1}[a-z0-9]+)_.[a-z]{2,5}(:[0-9]{1,5})?(/._)?$
Returns **[Validator](#validator)** this for chaining.
#### boolean
- **See: [instance](instance)**
Shortcut for instance('Boolean')
Returns **[Validator](#validator)** this for chaining.
#### number
- **See: [instance](instance)**
Shortcut for instance('Number')
Returns **[Validator](#validator)** this for chaining.
#### integer
- **See: [Number.isInteger](Number.isInteger)**
Validate that value is an integer.
Returns **[Validator](#validator)** this for chaining.
#### string
- **See: [instance](instance)**
Shortcut for instance('String')
Returns **[Validator](#validator)** this for chaining.
#### object
- **See: [instance](instance)**
Shortcut for instance('Object')
Returns **[Validator](#validator)** this for chaining.
#### array
- **See: [Array.isArray](Array.isArray)**
Validate that value is an array.
Returns **[Validator](#validator)** this for chaining.
#### function
- **See: [ChainApplier](ChainApplier)**
Shortcut for instance('Function')
Returns **[Validator](#validator)** this for chaining.
#### length
If arg is a Number, validate length is equals to arg.<br/>
Else arg must be a function then it's a shortcut for keys('length', arg).<br/>
```javascript
// Exemple:
Validator(procs, 'procs').array().length(4);
Validator(name, 'name').string().length(vLength => vlength.greaterThan(3).not.greaterThan(20));
```
##### Parameters
- `arg` **([Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) | ChainApplier)** Exact length to compare with or function for length validation chain.
Returns **[Validator](#validator)** this for chaining.
#### each
Apply given validation chain to each element in the value array.<br/>
Doesn't validate that value is effectively an array.<br/>
each must not be used with not modifier.<br/>
```javascript
// Exemple:
Validator(names, 'names').each(vName => vName.string().match(/^[\w-']{4,20}$/));
```
##### Parameters
- `apply` **ChainApplier** Function validation chain
Returns **[Validator](#validator)** this for chaining.
#### keys
Validate each give child key associated chainApplier.<br/>
If key is missing then DOESNT_EXISTS error id thrown unless optional is set to true then chainApplier isn't called.<br/>
keys must not be used with not modifier.<br/>
```javascript
// Exemple:
Validator(customer, 'customer').keys(
{ key: 'id', chain: vId => vId.integer().not.equal(0) },
{ key: 'name', chain: vName => vName.string().length(vLength => vlength.greaterThan(3).not.greaterThan(20)).match(/^[\w-']$/) },
{ key: 'email', chain: vEmail => vEmail.string().match(/^[\w]+@[\w]+\.[\w]{2,}$/) },
{ key: 'age', optional: true, chain: vAge => vAge.integer().greaterThan(0).not.greaterThan(130) },
);
```
##### Parameters
- `args` **...([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** List of object with properties key(String) and chain(chainApplier). Also accept String, then validate child property exists<br/>
args are deeply flatten, you can provided any kind of nested array structure as long as leafs are valid argument.<br/>
As well all falsy value are ignored (undefined, false, 0, '', null).
Returns **[Validator](#validator)** this for chaining.
#### or
Create node from which many chains starts. Chain is invalidated only if all sub chains are invalidated.
```javascript
// Exemple:
Validator(innate, 'innate').or(
vInnate => vInnate.boolean(),
vInnate => vInnate.string().among(EFFECTS),
vInnate => vInnate.object().keys('effect', 'value', (vEffect, vValue) => {
vEffect.string().among(EFFECTS);
vValue.integer().not.lowerThan(5).not.greaterThan(8);
})
);
```
##### Parameters
- `args` **...ChainApplier** List of subsequence chain. First parameter will be this validator.
Returns **[Validator](#validator)** this for chaining.
#### try
Throw responsible error if chain is invalid.
Returns **[Validator](#validator)** this for chaining.
#### resolve
Reject with responsible error if chain is invalid. Resolve without value otherwise.
Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)** Bluebird promise