Tiny Validator for v4 JSON Schema

Download full (17kb) or minified (8.3kb, 2.86kb gzipped)

Tiny Validator is a JavaScript library for validation against v4 the JSON Schema standard.

It supports $ref with JSON Pointer fragment paths (e.g. http://example.com/schema#/properties/myKey).

It uses relatively modern JavaScript features (such as JSON.stringify and Array.isArray) so older browsers will need a compatability shim - this is a good one.

For the source code, see the GitHub repository.

Usage:

var valid = tv4.validate(data, schema);

If validation fails, there will be an object describing the error in tv4.error. If there are any schemas missing ($refs not resolved), then they will be present in tv4.missing.

Missing schemas are treated as empty.

Demos:

Basic usage

run demo
var schema = {
	"items": {
		"type": "boolean"
	}
};
var data1 = [true, false];
var data2 = [true, 123];

alert("data 1: " + tv4.validate(data1, schema)); // true
alert("data 2: " + tv4.validate(data2, schema)); // false
alert("data 2 error: " + JSON.stringify(tv4.error, null, 4));

Use of $ref

run demo
var schema = {
	"type": "array",
	"items": {"$ref": "#"}
};
var data1 = [[], [[]]];
var data2 = [[], [true, []]];

alert("data 1: " + tv4.validate(data1, schema)); // true
alert("data 2: " + tv4.validate(data2, schema)); // false

Missing schema

run demo
var schema = {
	"type": "array",
	"items": {"$ref": "http://example.com/schema"}
};
var data = [1, 2, 3];

alert("Valid: " + tv4.validate(data, schema)); // true
alert("Missing schemas: " + JSON.stringify(tv4.missing));

Referencing remote schema

run demo
tv4.addSchema("http://example.com/schema", {
	"definitions": {
		"arrayItem": {"type": "boolean"}
	}
});
var schema = {
	"type": "array",
	"items": {"$ref": "http://example.com/schema#/definitions/arrayItem"}
};
var data1 = [true, false, true];
var data2 = [1, 2, 3];

alert("data 1: " + tv4.validate(data1, schema)); // true
alert("data 2: " + tv4.validate(data2, schema)); // false

Asynchronous usage:

Asynchronous usage (fetching schemas using AJAX) requires an additional file. Currently, the only version available relies on jQuery, but it is short and should be easily modifiable for other libraries: tv4.async-jquery.js

Asynchronous mode is signified by providing a callback as a third parameter:

tv4.validate(data, schema, function (isValid, validationError) { ... });

The value of validationError is taken from tv4.error.

Tests:

There are some tests, but they use PHP to run, so they won't work when hosted by GitHub.