peerlibrary/tv4

Name: tv4

Owner: PeerLibrary

Description: Tiny Validator for JSON Schema v4

Created: 2015-02-27 03:02:02.0

Updated: 2015-02-27 03:02:03.0

Pushed: 2015-02-25 12:18:27.0

Homepage: http://geraintluff.github.com/tv4/

Size: 1770

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

Tiny Validator (for v4 JSON Schema)

Build Status Dependency Status NPM version

Use json-schema draft v4 to validate simple values and complex objects using a rich validation vocabulary (examples).

There is support for $ref with JSON Pointer fragment paths (`other-schema.json#/properties/myKey`).

Usage 1: Simple validation
valid = tv4.validate(data, schema);

If validation returns `false, then an explanation of why validation failed can be found in ``tv4.error```.

The error object will look something like:


"code": 0,
"message": "Invalid type: string",
"dataPath": "/intKey",
"schemaPath": "/properties/intKey/type"

The "code" property will refer to one of the values in tv4.errorCodes - in this case, tv4.errorCodes.INVALID_TYPE.

To enable external schema to be referenced, you use:

addSchema(url, schema);

If schemas are referenced (`$ref) but not known, then validation will return ``true` and the missing schema(s) will be listed intv4.missing``. For more info see the API documentation below.

Usage 2: Multi-threaded validation

Storing the error and missing schemas does not work well in multi-threaded environments, so there is an alternative syntax:

result = tv4.validateResult(data, schema);

The result will look something like:


"valid": false,
"error": {...},
"missing": [...]

Usage 3: Multiple errors

Normally, tv4 stops when it encounters the first validation error. However, you can collect an array of validation errors using:

result = tv4.validateMultiple(data, schema);

The result will look something like:


"valid": false,
"errors": [
    {...},
    ...
],
"missing": [...]

Asynchronous validation

Support for asynchronous validation (where missing schemas are fetched) can be added by including an extra JavaScript file. Currently, the only version requires jQuery (tv4.async-jquery.js), but the code is very short and should be fairly easy to modify for other libraries (such as MooTools).

Usage:

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

validationFailure is simply taken from tv4.error.

Cyclical JavaScript objects

While they don't occur in proper JSON, JavaScript does support self-referencing objects. Any of the above calls support an optional third argument: checkRecursive. If true, tv4 will handle self-referencing objects properly - this slows down validation slightly, but that's better than a hanging script.

Consider this data, notice how both a and b refer to each other:

a = {};
b = { a: a };
= b;
aSchema = { properties: { b: { $ref: 'bSchema' }}};
bSchema = { properties: { a: { $ref: 'aSchema' }}};
addSchema('aSchema', aSchema);
addSchema('bSchema', bSchema);

If the checkRecursive argument were missing, this would throw a “too much recursion” error.

To enable support for this, pass true as additional argument to any of the regular validation methods:

validate(a, aSchema, true);
validateResult(data, aSchema, true); 
validateMultiple(data, aSchema, true);
The banUnknownProperties flag

Sometimes, it is desirable to flag all unknown properties as an error. This is especially useful during development, to catch typos and the like, even when extra custom-defined properties are allowed.

As such, tv4 implements “ban unknown properties” mode, enabled by a fourth-argument flag:

validate(data, schema, checkRecursive, true);
validateResult(data, schema, checkRecursive, true);
validateMultiple(data, schema, checkRecursive, true);
API

There are additional api commands available for more complex use-cases:

addSchema(uri, schema)

Pre-register a schema for reference by other schema and synchronous validation.

addSchema('http://example.com/schema', { ... });

Schemas that have their id property set can be added directly.

addSchema({ ... });
getSchema(uri)

Return a schema from the cache.

schema = tv4.getSchema('http://example.com/schema');
getSchemaMap()

Return a shallow copy of the schema cache, mapping schema document URIs to schema objects.

map = tv4.getSchemaMap();

schema = map[uri];
getSchemaUris(filter)

Return an Array with known schema document URIs.

arr = tv4.getSchemaUris();

ptional filter using a RegExp
arr = tv4.getSchemaUris(/^https?://example.com/);
getMissingUris(filter)

Return an Array with schema document URIs that are used as $ref in known schemas but which currently have no associated schema data.

Use this in combination with tv4.addSchema(uri, schema) to preload the cache for complete synchronous validation with.

arr = tv4.getMissingUris();

ptional filter using a RegExp
arr = tv4.getMissingUris(/^https?://example.com/);
dropSchemas()

Drop all known schema document URIs from the cache.

dropSchemas();
freshApi()

Return a new tv4 instance with no shared state.

otherTV4 = tv4.freshApi();
reset()

Manually reset validation status from the simple tv4.validate(data, schema). Although tv4 will self reset on each validation there are some implementation scenarios where this is useful.

reset();
language(code)

Select the language map used for reporting.

language('en-gb');
addLanguage(code, map)

Add a new language map for selection by tv4.language(code)

addLanguage('fr', { ... });

elect for use
language('fr')
addFormat(format, validationFunction)

Add a custom format validator. (There are no built-in format validators. Several common ones can be found here though)

addFormat('decimal-digits', function (data, schema) {
if (typeof data === 'string' && !/^[0-9]+$/.test(data)) {
    return null;
}
return "must be string of decimal digits";

Alternatively, multiple formats can be added at the same time using an object:

addFormat({
'my-format': function () {...},
'other-format': function () {...}

defineKeyword(keyword, validationFunction)

Add a custom keyword validator.

defineKeyword('my-custom-keyword', function (data, value, schema) {
if (simpleFailure()) {
    return "Failure";
} else if (detailedFailure()) {
    return {code: tv4.errorCodes.MY_CUSTOM_CODE, message: {param1: 'a', param2: 'b'}};
} else {
    return null;
}

schema is the schema upon which the keyword is defined. In the above example, value === schema['my-custom-keyword'].

If an object is returned from the custom validator, and its message is a string, then that is used as the message result. If message is an object, then that is used to populate the (localisable) error template.

defineError(codeName, codeNumber, defaultMessage)

Defines a custom error code.

An example of defaultMessage might be: "Incorrect moon (expected {expected}, got {actual}"). This is filled out if a custom keyword returns a object message (see above). Translations will be used, if associated with the correct code name/number.

Demos
Basic usage
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
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
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
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
Supported platforms
Installation

You can manually download tv4.js or the minified tv4.min.js and include it in your html to create the global tv4 variable.

Alternately use it as a CommonJS module:

tv4 = require('tv4');

or as an AMD module (e.g. with requirejs):

ire('tv4', function(tv4){
use tv4 here

npm
m install tv4
bower
wer install tv4
component.io
mponent install geraintluff/tv4
Build and test

You can rebuild and run the node and browser tests using node.js and grunt:

Make sure you have the global grunt cli command:

m install grunt-cli -g

Clone the git repos, open a shell in the root folder and install the development dependencies:

m install

Rebuild and run the tests:

unt

It will run a build and display one Spec-style report for the node.js and two Dot-style reports for both the plain and minified browser tests (via phantomJS). You can also use your own browser to manually run the suites by opening test/index.html and test/index-min.html.

Contributing

Pull-requests for fixes and expansions are welcome. Edit the partial files in /source and add your tests in a suitable suite or folder under /test/tests and run grunt to rebuild and run the test suite. Try to maintain an idiomatic coding style and add tests for any new features. It is recommend to discuss big changes in an Issue.

Do you speak another language? tv4 needs internationalisation - please contribute language files to /lang!

Packages using tv4
License

The code is available as “public domain”, meaning that it is completely free to use, without any restrictions at all. Read the full license here.

It's also available under an MIT license.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.