validate-params-schema
Parameter validation for builtins and custom types. Accepts params
and a schema
and returns an array of Error
s or false
.
var validate = { var schema = 'name': required:true type:Object 'name.first': required:true type:String 'name.last': required:false type:String var errors = if errors else } // logs: null, hi brian // logs: [ [ReferenceError: missing required param name.first] ]
considerations
- For testing an
Object
that presumably came from a JSON payload - Thusly, primarily concerned with JSON value types:
Object
,String
,Number
,Array
andBoolean
- Custom types are easily supported (see
./examples
) - Designed to test keys and nested keys
- Optionally validate
required
- Optionally validate
min
andmax
forString
,Number
andArray
builtin types (and easily implement for custom types)
things it does not do
- mutate things with: serialization, formatting or defaults
- nested subtypes (eg. the things in an array)
- localized error messages
further justifications
There are a tonne of libraries that do things like this but also do a whole lot more. This library deliberately limits its scope: make errback style param contract validation super clean and simple. Work primarily with builtins but easily extend. Provide a nice API for usage (hence returning false instead of a truthy empty array for the return value of validate).
example usage
var validate = functon { // define our assumed params var errors = // err first! if errors else }
api
validate(params, schema)
params
a plain old javascript object that we assume came from JSONschema
a plain javascript object for describing the shape of the data
schema keys
required
eithertrue
orfalse
(or leave it out completely)type
can be one ofObject
,String
,Number
,Array
andBoolean
min
anyNumber
(or anything allowed by a custom type)max
anyNumber
(or anything allowed by a custom type)
Check out ./examples
for more on custom types and ranges (and the tests).