fans-warden
A promise based 'React PropType' inspired JavaScript object validator.
Getting started
npm install --save fans-warden
Usage
Here is a cookie cutter example on how to use fans-warden:
; const rules = prop1: Typesstring prop2: TypesboolisRequired prop3: Types prop6: TypesisRequired prop7: Types prop10: Typesshape prop11: Typesfunc prop12: TypesfuncisRequired; const data = ...; // the data you want to validate based on your rules ;
Types
The different Types available for use are the following:
Types.string
Types.number
Types.bool
Types.array
Types.shape
Types.func
Types.arrayOf()
Types.shapeOf()
By adding .isRequired
at the end of the rule (ex: Types.string.isRequired
), the validation will now fail if the property is not present in the object to validate.
Types.arrayOf()
Types.arrayOf()
takes an argument, which needs to be any possible Type
(even Types.arrayOf()
). The validation will fail if the array contains an element having a different type than the provided Type
.
see example above
Types.shapeOf()
Types.shapeOf()
takes an argument, which needs to be an object
({}
). This object can implement keys with additional rules that you want to apply, making a deep validation.
see example above
values()
By adding the values(array)
method, the data now has to be present inside the array
passed to values()
, or else the validation fails.
You can also combinate values(array)
to isRequired
.
Here are the different Types that support values(array)
:
Types.string
Types.number
Types.bool
Types.array
Types.arrayOf()
example
; const rules = prop1: TypesstringisRequired prop2: TypesnumberisRequired prop3: Typesarray prop4: Types prop5: Types prop6: Types; const data = ...; // the data you want to validate based on your rules ;
min(), max(), range()
By adding a range method on a Types.number
such as min(x)
, max(y)
or range(x, y)
, you define maximum and minimum values for the number. The validation will now fail if the value is smaller or greater than the provided ranges.
You can also combinate the range methods to values(array)
and isRequired
.
example
; const rules = prop1: Typesnumber prop2: Typesnumber prop3: Typesnumber prop4: Typesnumber prop5: Types prop6: Types prop7: Types prop8: Types; const data = ...; // the data you want to validate based on your rules ;