Module Validator
Usage
With throw try catch
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
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) => {
});
}
Express/Koa control body
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
Table of Contents
- callbacks
- instanceOf
- isInstance
- mustBeInstance
- Validator
callbacks
ErrorBuilder
Function building error.
Returns Error Responsible error.
Checker
Function checking if "value" is valid or not
Parameters
-
value
any Value to check.
Returns Boolean true if valid, false otherwise.
ChainApplier
Function appling chain validation on parameter.
Parameters
-
Validator
Validator to apply chain on.
instanceOf
Access 'constructor.name'.
if undefined or null, return 'undefined'
Parameters
-
data
any argument
Returns String Type name, one of 'undefined', 'Boolean', 'Number', 'String', 'Array', 'Object', 'Function', '${ClassName}'
isInstance
- See: instanceOf
Compare if item is an element of expectedType. Allow inheritance.
Parameters
-
item
any Element for which type is checked. -
expectedInstance
(String | Function) String representation or constructor of type to looking for
Returns Boolean true if item or its ancestry is type of expectedType.
mustBeInstance
Compare if item is an element of expectedType. Allow inheritance.
Throw error if failed.
Parameters
-
item
any Element for which type is checked. -
expectedInstance
(String | Function) String representation or constructor of type to looking for -
name
String Name of item for error building
Returns undefined
Validator
isValid
Return if chain is valid or invalidated
Returns 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 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, defaultbuildError
)
Returns Validator this for chaining.
setModifier
Change modifier state. true for normal validation, false for reverse validation.
Parameters
-
modifier
Boolean Boolean value for modifier.
Returns Validator this for chaining.
resetModifier
Set modifier back to true (normal validation).
Returns Validator this for chaining.
not
Reverse modifier
Returns Validator this for chaining.
apply
Execute "chain" with this validator.
Parameters
-
chain
ChainApplier Function appling chain validation.
Returns Validator this for chaining.
exist
- See: instanceOf
Validate that value exists excluding undefined and null.
Returns Validator this for chaining.
type
Validate that value type is equal to expectedType. According to typeof.
Parameters
-
expectedType
String Type description string ('undefined', 'boolean', 'number', 'string', 'object').
Returns Validator this for chaining.
instance
- See: isInstance
- See: or
Validate that value instance is equals to expectedInstance. According to isInstance.
Parameters
-
expectedType
(String | Function) Type description string ('Boolean', 'Number', 'String', 'Object', Object, Error, ...).
Returns Validator this for chaining.
equal
- See: lodash#isEqual
Validate that value is equal to parameter according to lodash#isEqual
Parameters
-
value
any Value to compare with.
Returns Validator this for chaining.
among
Validate that value is included in parameter values.
Parameters
-
values
Array<any> Values to look through.
Returns Validator this for chaining.
greaterThan
Validate that value is greater than limit parameter (excluded).
Use reverse function not.lowerThan to include limit.
Parameters
-
limit
Number Limit parameter.
Returns Validator this for chaining.
lowerThan
Validate that value is lower than limit parameter (excluded).
Use reverse function not.greaterThan to include limit.
Parameters
-
limit
Number Limit parameter.
Returns Validator this for chaining.
greaterOrEqualThan
Shortcut for not.lowerThan(limit)
Parameters
-
limit
Number Limit parameter.
Returns Validator this for chaining.
lowerOrEqualThan
Shortcut for not.greaterThan(limit)
Parameters
-
limit
Number Limit parameter.
Returns Validator this for chaining.
match
Validate that value match given regexp
Parameters
-
regex
RegExp RegExp to validate.
Returns Validator this for chaining.
startsWith
- See: String#startsWith
Validate that value startsWith given sub string.
Parameters
-
needle
String Sub string to look for.
Returns Validator this for chaining.
endsWith
- See: String#endsWith
Validate that value endsWith given sub string.
Parameters
-
needle
String Sub string to look for.
Returns Validator this for chaining.
hexadecimal
Validate that value contains hexadecimal character only and it's length is even.
Shortcut for match(/^([0-9a-fA-F]{2})*$/).
Returns Validator this for chaining.
base64
Validate that value contains base64 character only and it's length is valid for base64.
Shortcut for match(/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2,3}==?)?$/).
Returns Validator this for chaining.
url
Validate that value is an url.
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 this for chaining.
boolean
- See: instance
Shortcut for instance('Boolean')
Returns Validator this for chaining.
number
- See: instance
Shortcut for instance('Number')
Returns Validator this for chaining.
integer
- See: Number.isInteger
Validate that value is an integer.
Returns Validator this for chaining.
string
- See: instance
Shortcut for instance('String')
Returns Validator this for chaining.
object
- See: instance
Shortcut for instance('Object')
Returns Validator this for chaining.
array
- See: Array.isArray
Validate that value is an array.
Returns Validator this for chaining.
function
- See: ChainApplier
Shortcut for instance('Function')
Returns Validator this for chaining.
length
If arg is a Number, validate length is equals to arg.
Else arg must be a function then it's a shortcut for keys('length', arg).
// Exemple:
Validator(procs, 'procs').array().length(4);
Validator(name, 'name').string().length(vLength => vlength.greaterThan(3).not.greaterThan(20));
Parameters
-
arg
(Number | ChainApplier) Exact length to compare with or function for length validation chain.
Returns Validator this for chaining.
each
Apply given validation chain to each element in the value array.
Doesn't validate that value is effectively an array.
each must not be used with not modifier.
// Exemple:
Validator(names, 'names').each(vName => vName.string().match(/^[\w-']{4,20}$/));
Parameters
-
apply
ChainApplier Function validation chain
Returns Validator this for chaining.
keys
Validate each give child key associated chainApplier.
If key is missing then DOESNT_EXISTS error id thrown unless optional is set to true then chainApplier isn't called.
keys must not be used with not modifier.
// 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 | Object) List of object with properties key(String) and chain(chainApplier). Also accept String, then validate child property exists
args are deeply flatten, you can provided any kind of nested array structure as long as leafs are valid argument.
As well all falsy value are ignored (undefined, false, 0, '', null).
Returns Validator this for chaining.
or
Create node from which many chains starts. Chain is invalidated only if all sub chains are invalidated.
// 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 this for chaining.
try
Throw responsible error if chain is invalid.
Returns Validator this for chaining.
resolve
Reject with responsible error if chain is invalid. Resolve without value otherwise.
Returns Promise Bluebird promise