JSON Schema validation v0.3.0
Installation
$ npm install skerla-json-schema
Schema
Constructor
new V.Schema(schema: Object|Array|Rule): Schema
Methods
validate(object: Object|Array): ValidationResult
validates a given object and returns an instances of ValidationResult
getSpecs(): Object
Returns an object describing specification of the schema.
Usage example
General usecase
const V = ;const validation = id: status: items: ; const validationResult = validation; validationResult; //true
Advanced
const V = ;const validation = ; validation; //falsevalidation; //falsevalidation; //falsevalidation; //true
ValidationResult
Methods
isValid(): Boolean
Returns if the object has passed validation process
getErrors(): Array{errno: Number, path: string, message: String}
Returns validation errors
const V = ;const validation = id: name: surname: ; const validationResult = validation; const isValid = validationResult; //falseconst errors = validationResult; /*[ { errno: 2, path: 'id', message: 'type of the value must be Number, got String.' }, { errno: 6, path: 'name', message: 'the length must be >= 3, got 2.' }, { errno: 1, path: 'surname', message: 'required' } ]*/
cleanup(): Object
Removes all properties in a nested object which are not defined in the schema.
const V = ;const validation = name: surname: address: city: ; const validationResult = validation; const cleanedUp = validationResult;/* returns{ name: 'Andrius', surname: 'Skerla, address: { city: 'London' }};*/
Rule
Methods
required(value: Boolean = true): Rule
Defines if the property can not be undefined
min(value: Number): Rule
Defines min length of a String or an Array, or min Number value.
max(value: Number): Rule
Defines max length of a String or an Array, or max Number value.
len(value: Number): Rule
Defines a length of a String or an Array
match(value: RegExp): Rule
Defines a pattern of a string
const validation = number: ;
oneOf(values: Array): Rule
Defines a set of possible values for String, Number and Array.
const validation = type: directions: ; validation; //true
typeOf(constructor: Function): Rule
Defines a type of a item in an array
items:
schema(schema: Object): Rule
Defines a schema of an array or a nested object
null(): Rule
Allows a property to have null
value.
address: //property must be defined and be either null either String
check(path: String, value: mixed): ValidationResult; throws RuleError
Usage Example
const Rule = ;const rule = String; rule; //truerule; //throws