mgl-validate
data object validation
mgl-validate is a library for validating any variable type, including objects, arrays and primitives, as well as mixed type definitions.
Moreover, mgl-validate enables the programmer to verify the validity of complex & deeply nested object structures. The library features defining validation schemas to be used as references, hence facilitating shared and reusable definitions upon which complex and possibly nested validation schemas can be built.
Schemas are compiled at time of definition to keep performance penalties of actual validations at a minimum.
Stability: 3 - Stable
Table of Contents
Testimonials
I really like the notion of adding a schema and referencing it in others - that's just super-cool
Example
var registry = breakOnError: true; try // create a nested schema registry; catch err return console; var errors; // validate against 'doc'errors = registry;if errors console; // ... or validate directly against 'uuid'errors = registry;if errors console;
Types
null
boolean
number
integer
- validates asnumber
toostring
array
object
buffer
function
mixed
Schema
See tests
for examples covering all use cases.
The options are processed in the following order; type optional value min < max < enum < pattern properties
, where A < B
means that B
is only tested when A
didn't fail.
properties
{?string=} id
- The schema id, when given the schema can be referenced{string} type
- The data type; See Types{?number=} depth
- Absolute nesting limit for validated data, defaults to10
{?boolean=} optional
- Whentrue
, the value may beundefined
{?*=} default
- A default value, impliesoptional: true
{?string=} pattern
- An encoded regular-expression for string validation{?string=} flags
- Regular-expression flags{?number=} min
- Minimum number of chars, elements, properties, arguments{?number=} max
- Maximum number of chars, elements, properties, arguments{?Object<string, (Object|string)>=} properties
- A map with schemas for each property of an object{?boolean=} allowUnknownProperties
- Whentrue
, an object may contain properties that don't have a schema{?(Array|Object|string)=} enum
- Validate values against given primitives and/or schemas{?boolean=} ordered
- Whentrue
, an array is matched againstenum
in order{?boolean=} allowNullValue
- Whentrue
, the affected schema's value may benull
enum
Validate values against given values and/or schemas.
NOTE: The most likely values should be placed at the top of the enum array to improve validation performance.
Types: number
, integer
, string
, array
, mixed
Primitives
Primitive data types can be validated against a list of static values of their own type;
type: 'number' // or 'integer' or 'string' enum: 1 2 3
type: array
Arrays support multiple combinations for enum
;
... a single schema, either as reference ($id:<name>
) or object. All elements in the array now have to comply to the given schema.
type: 'array' enum: '$id:uuid'
... an array of schemas and/or primitives. Any element in the array has to comply to any of the supplied schemas. When ordered: true
, the elements of the array have to comply to the given schemas in order.
type: 'array' ordered: true enum: '$id:uuid' false type: 'integer'
In the above example the 2nd, 5th, 8th, ... element of any array has to be false
in order to pass the test
Validation restarts at the first element of the given enum
if the number of elements t.b. validated exceeds the given schemas.
This behaviour can be further controlled with the min
and max
options.
type: mixed
enum
for type: mixed
works exactly like for type: array
with an array of schemas and/or primitives, but in respect to a single value.
properties
An object with properties where each value is a primitive value, schema object or reference.
Types: object
, function
type: 'object' properties: xyz: type: 'number' abc: '$id:other' // has to match "other" schema wtf: 'abc' // primitive equals match ...
wildcard
Types: object
type: 'object' properties: '*': // all unknown properties have to match this schema type: 'string' ... ...
min & max
A number that describes the minimum ...
- value for a
number
or aninteger
- length for a
string
- length for an
array
- number of arguments for a
function
- number of properties on an
object
Types: number
, integer
, string
, array
, object
, function
Note: When min
fails, the test for max
is omitted for logical reasons.
pattern
A string to be used for new RegExp()
.
Types: string
flags
Types: string
optional
When true
the value may be undefined
, type violations other than undefined
produce an error.
Types: ALL
default
Works ONLY for object properties!
Apply a default value if undefined
.
Types: number
, integer
, string
, array
, function
allowUnknownProperties
Allows an object to have properties not specified in the schema.
Defaults to true
for function
and to false
for object
.
Types: object
, function
API
Class: Registry
new Registry(opt_options)
{?Object=} opt_options
{?boolean=} breakOnError
- defaults tofalse
{?number=} depth
- Global nesting limit, defaults to10
. Can be overridden by each schema
registry.breakOnError
registry.getSchemas()
registry.addSchema(definition)
registry.removeSchema(schema)
registry.test(schema, data);
See schema.test()
.
Class: Schema
new Schema(registry, definition)
schema.test(data)
Validate given data, returns validation errors as array, null
otherwise.
An annotated example;
<pathToValue> <expectedType> <reason> <offendingValue> // property b of object a is undefined 'a' 'object' 'undefined' 'b' // property c of object a is not of type string 'a.c' 'string' 'type' 2 // property e of the 1st element of the array at property d of object a is too small 'a.d.0.e' 'number' 'min' -1 ...
schema.typeOf(value)
Tests
npm testfirefox coverage/lcov-report/index.html
Coverage
Statements : 99.37% ( 317/319 )
Branches : 97.74% ( 260/266 )
Functions : 100% ( 21/21 )
Lines : 99.37% ( 317/319 )
License
(The MIT license)
Copyright (c) 2015 Magora Group GmbH, Austria (www.magora.at)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.