File: index.html

package info (click to toggle)
libjs-tv4 1.2.7+dfsg1-2.1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 5,464 kB
  • sloc: javascript: 107,382; makefile: 16
file content (415 lines) | stat: -rw-r--r-- 21,725 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
<html>
<head>
    <title>Tiny Validator for v4 JSON Schema</title>
    <style>
        body {
            background-color: #F0F0E0;
            font-family: sans-serif;
        }

        a {
            color: #04D;
            text-decoration: none;
        }

        a:hover {
            color: #08F;
            text-decoration: underline;
        }

        #main {
            width: 780px;
            margin-left: auto;
            margin-right: auto;
            border: 1px solid #888;
            border-radius: 3px;
            background-color: #FFF;
        }

        h1 {
            text-align: center;
            font-size: 1.4em;
            font-weight: bold;
            border-bottom: 1px solid black;
            margin: 0;
            padding: 0.3em;
            padding-left: 1em;
            background-color: #F8F8F0;
            border-top-left-radius: 3px;
            border-top-right-radius: 3px;
        }

        h2 {
            border-bottom: 1px solid #BBB;
        }

        h2, h3, h4{
            padding-left: .8em;
            padding-right: .8em;
        }
        h5, p, pre, ul, ol, .content {
            padding-left: 1em;
            padding-right: 1em;
        }
        li {
            margin-left: 1em;
            margin-right: 1em;
        }
        code, .code {
            background-color: #F8F8F8;
            border: 1px solid #DDD;
            border-radius: 3px;
            padding:.1em .2em;
        }
        pre code {
            display:block;
            margin:5px;
            padding:.5em;
        }
    </style>
</head>
<body onload="enableDemos();">
<script src="tv4.js"></script>
<script>
    function enableDemos() {
        if (!document.querySelectorAll) {
            return;
        }
        var demos = document.querySelectorAll(".inline-demo");
        if (!demos || demos.length === 0) {
            return;
        }
        for (var i = 0, ii = demos.length; i < ii; i++) {
            linkDemo(demos[i]);
        }
    }
    function linkDemo(demo) {
        var id = demo.dataset['demo'];
        var a = document.createElement('a');
        a.appendChild(document.createTextNode('run demo'));
        a.href = "javascript:runDemo('" + id + "');";
        demo.insertBefore(a, demo.firstChild);
    }

    function getDeepNodeValue(element) {
        var text = "";
        for (var i = 0, ii = element.childNodes.length; i < ii; i++) {
            var child = element.childNodes[i];
            if (child.nodeType === 3) {
                text += child.nodeValue;
            }
            else if (child.nodeType === 1){
                text += getDeepNodeValue(child);
            }
        }
        return text;
    }

    function runDemo(elementId) {
        var element = document.getElementById(elementId);
        eval(getDeepNodeValue(element));
    }
</script>
<div id="main">
<h1 id="tiny-validator-for-v4-json-schema-">Tiny Validator (for v4 JSON Schema)</h1>
<p><a href="http://travis-ci.org/geraintluff/tv4"><img src="https://secure.travis-ci.org/geraintluff/tv4.svg?branch=master" alt="Build Status"></a> <a href="https://gemnasium.com/geraintluff/tv4"><img src="https://gemnasium.com/geraintluff/tv4.svg" alt="Dependency Status"></a> <a href="http://badge.fury.io/js/tv4"><img src="https://badge.fury.io/js/tv4.svg" alt="NPM version"></a></p>
<p>Use <a href="http://json-schema.org/">json-schema</a> <a href="http://json-schema.org/latest/json-schema-core.html">draft v4</a> to validate simple values and complex objects using a rich <a href="http://json-schema.org/latest/json-schema-validation.html">validation vocabulary</a> (<a href="http://json-schema.org/examples.html">examples</a>).</p>
<p>There is support for <code>$ref</code> with JSON Pointer fragment paths (<code>other-schema.json#/properties/myKey</code>).</p>
<h2 id="usage-1-simple-validation">Usage 1: Simple validation</h2>
<pre><code class="lang-javascript">var valid = tv4.validate(data, schema);</code></pre>
<p>If validation returns <code>false</code>, then an explanation of why validation failed can be found in <code>tv4.error</code>.</p>
<p>The error object will look something like:</p>
<pre><code class="lang-json">{
    &quot;code&quot;: 0,
    &quot;message&quot;: &quot;Invalid type: string&quot;,
    &quot;dataPath&quot;: &quot;/intKey&quot;,
    &quot;schemaPath&quot;: &quot;/properties/intKey/type&quot;
}</code></pre>
<p>The <code>&quot;code&quot;</code> property will refer to one of the values in <code>tv4.errorCodes</code> - in this case, <code>tv4.errorCodes.INVALID_TYPE</code>.</p>
<p>To enable external schema to be referenced, you use:</p>
<pre><code class="lang-javascript">tv4.addSchema(url, schema);</code></pre>
<p>If schemas are referenced (<code>$ref</code>) but not known, then validation will return <code>true</code> and the missing schema(s) will be listed in <code>tv4.missing</code>. For more info see the API documentation below.</p>
<h2 id="usage-2-multi-threaded-validation">Usage 2: Multi-threaded validation</h2>
<p>Storing the error and missing schemas does not work well in multi-threaded environments, so there is an alternative syntax:</p>
<pre><code class="lang-javascript">var result = tv4.validateResult(data, schema);</code></pre>
<p>The result will look something like:</p>
<pre><code class="lang-json">{
    &quot;valid&quot;: false,
    &quot;error&quot;: {...},
    &quot;missing&quot;: [...]
}</code></pre>
<h2 id="usage-3-multiple-errors">Usage 3: Multiple errors</h2>
<p>Normally, <code>tv4</code> stops when it encounters the first validation error.  However, you can collect an array of validation errors using:</p>
<pre><code class="lang-javascript">var result = tv4.validateMultiple(data, schema);</code></pre>
<p>The result will look something like:</p>
<pre><code class="lang-json">{
    &quot;valid&quot;: false,
    &quot;errors&quot;: [
        {...},
        ...
    ],
    &quot;missing&quot;: [...]
}</code></pre>
<h2 id="asynchronous-validation">Asynchronous validation</h2>
<p>Support for asynchronous validation (where missing schemas are fetched) can be added by including an extra JavaScript file.  Currently, the only version requires jQuery (<code>tv4.async-jquery.js</code>), but the code is very short and should be fairly easy to modify for other libraries (such as MooTools).</p>
<p>Usage:</p>
<pre><code class="lang-javascript">tv4.validate(data, schema, function (isValid, validationError) { ... });</code></pre>
<p><code>validationFailure</code> is simply taken from <code>tv4.error</code>.</p>
<h2 id="cyclical-javascript-objects">Cyclical JavaScript objects</h2>
<p>While they don&#39;t occur in proper JSON, JavaScript does support self-referencing objects. Any of the above calls support an optional third argument: <code>checkRecursive</code>. If true, tv4 will handle self-referencing objects properly - this slows down validation slightly, but that&#39;s better than a hanging script.</p>
<p>Consider this data, notice how both <code>a</code> and <code>b</code> refer to each other:</p>
<pre><code class="lang-javascript">var a = {};
var b = { a: a };
a.b = b;
var aSchema = { properties: { b: { $ref: &#39;bSchema&#39; }}};
var bSchema = { properties: { a: { $ref: &#39;aSchema&#39; }}};
tv4.addSchema(&#39;aSchema&#39;, aSchema);
tv4.addSchema(&#39;bSchema&#39;, bSchema);</code></pre>
<p>If the <code>checkRecursive</code> argument were missing, this would throw a &quot;too much recursion&quot; error.</p>
<p>To enable support for this, pass <code>true</code> as additional argument to any of the regular validation methods:</p>
<pre><code class="lang-javascript">tv4.validate(a, aSchema, true);
tv4.validateResult(data, aSchema, true);
tv4.validateMultiple(data, aSchema, true);</code></pre>
<h2 id="the-banunknownproperties-flag">The <code>banUnknownProperties</code> flag</h2>
<p>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.</p>
<p>As such, tv4 implements <a href="https://github.com/json-schema/json-schema/wiki/ban-unknown-properties-mode-\(v5-proposal\">&quot;ban unknown properties&quot; mode</a>), enabled by a fourth-argument flag:</p>
<pre><code class="lang-javascript">tv4.validate(data, schema, checkRecursive, true);
tv4.validateResult(data, schema, checkRecursive, true);
tv4.validateMultiple(data, schema, checkRecursive, true);</code></pre>
<h2 id="api">API</h2>
<p>There are additional api commands available for more complex use-cases:</p>
<h5 id="addschema-uri-schema-">addSchema(uri, schema)</h5>
<p>Pre-register a schema for reference by other schema and synchronous validation.</p>
<pre><code class="lang-js">tv4.addSchema(&#39;http://example.com/schema&#39;, { ... });</code></pre>
<ul>
<li><code>uri</code> the uri to identify this schema.</li>
<li><code>schema</code> the schema object.</li>
</ul>
<p>Schemas that have their <code>id</code> property set can be added directly.</p>
<pre><code class="lang-js">tv4.addSchema({ ... });</code></pre>
<h5 id="getschema-uri-">getSchema(uri)</h5>
<p>Return a schema from the cache.</p>
<ul>
<li><code>uri</code> the uri of the schema (may contain a <code>#</code> fragment)</li>
</ul>
<pre><code class="lang-js">var schema = tv4.getSchema(&#39;http://example.com/schema&#39;);</code></pre>
<h5 id="getschemamap-">getSchemaMap()</h5>
<p>Return a shallow copy of the schema cache, mapping schema document URIs to schema objects.</p>
<pre><code>var map = tv4.getSchemaMap();

var schema = map[uri];</code></pre>
<h5 id="getschemauris-filter-">getSchemaUris(filter)</h5>
<p>Return an Array with known schema document URIs.</p>
<ul>
<li><code>filter</code> optional RegExp to filter URIs</li>
</ul>
<pre><code>var arr = tv4.getSchemaUris();

// optional filter using a RegExp
var arr = tv4.getSchemaUris(/^https?://example.com/);</code></pre>
<h5 id="getmissinguris-filter-">getMissingUris(filter)</h5>
<p>Return an Array with schema document URIs that are used as <code>$ref</code> in known schemas but which currently have no associated schema data.</p>
<p>Use this in combination with <code>tv4.addSchema(uri, schema)</code> to preload the cache for complete synchronous validation with.</p>
<ul>
<li><code>filter</code> optional RegExp to filter URIs</li>
</ul>
<pre><code>var arr = tv4.getMissingUris();

// optional filter using a RegExp
var arr = tv4.getMissingUris(/^https?://example.com/);</code></pre>
<h5 id="dropschemas-">dropSchemas()</h5>
<p>Drop all known schema document URIs from the cache.</p>
<pre><code>tv4.dropSchemas();</code></pre>
<h5 id="freshapi-">freshApi()</h5>
<p>Return a new tv4 instance with no shared state.</p>
<pre><code>var otherTV4 = tv4.freshApi();</code></pre>
<h5 id="reset-">reset()</h5>
<p>Manually reset validation status from the simple <code>tv4.validate(data, schema)</code>. Although tv4 will self reset on each validation there are some implementation scenarios where this is useful.</p>
<pre><code>tv4.reset();</code></pre>
<h5 id="seterrorreporter-reporter-">setErrorReporter(reporter)</h5>
<p>Sets a custom error reporter.  This is a function that accepts three arguments, and returns an error message (string):</p>
<pre><code>tv4.setErrorReporter(function (error, data, schema) {
    return &quot;Error code: &quot; + error.code;
});</code></pre>
<p>The <code>error</code> object already has everything aside from the <code>.message</code> property filled in (so you can use <code>error.params</code>, <code>error.dataPath</code>, <code>error.schemaPath</code> etc.).</p>
<p>If nothing is returned (or the empty string), then it falls back to the default error reporter.  To remove a custom error reporter, call <code>tv4.setErrorReporter(null)</code>.</p>
<h5 id="language-code-">language(code)</h5>
<p>Sets the language used by the default error reporter.</p>
<ul>
<li><code>code</code> is a language code, like <code>&#39;en&#39;</code> or <code>&#39;en-gb&#39;</code></li>
</ul>
<pre><code>tv4.language(&#39;en-gb&#39;);</code></pre>
<p>If you specify a multi-level language code (e.g. <code>fr-CH</code>), then it will fall back to the generic version (<code>fr</code>) if needed.</p>
<h5 id="addlanguage-code-map-">addLanguage(code, map)</h5>
<p>Add a new template-based language map for the default error reporter (used by <code>tv4.language(code)</code>)</p>
<ul>
<li><code>code</code> is new language code</li>
<li><code>map</code> is an object mapping error IDs or constant names (e.g. <code>103</code> or <code>&quot;NUMBER_MAXIMUM&quot;</code>) to language strings.</li>
</ul>
<pre><code>tv4.addLanguage(&#39;fr&#39;, { ... });

// select for use
tv4.language(&#39;fr&#39;)</code></pre>
<p>If you register a multi-level language code (e.g. <code>fr-FR</code>), then it will also be registered for plain <code>fr</code> if that does not already exist.</p>
<h5 id="addformat-format-validationfunction-">addFormat(format, validationFunction)</h5>
<p>Add a custom format validator. (There are no built-in format validators. Several common ones can be found <a href="https://github.com/ikr/tv4-formats">here</a> though)</p>
<ul>
<li><code>format</code> is a string, corresponding to the <code>&quot;format&quot;</code> value in schemas.</li>
<li><code>validationFunction</code> is a function that either returns:<ul>
<li><code>null</code> (meaning no error)</li>
<li>an error string (explaining the reason for failure)</li>
</ul>
</li>
</ul>
<pre><code>tv4.addFormat(&#39;decimal-digits&#39;, function (data, schema) {
    if (typeof data === &#39;string&#39; &amp;&amp; !/^[0-9]+$/.test(data)) {
        return null;
    }
    return &quot;must be string of decimal digits&quot;;
});</code></pre>
<p>Alternatively, multiple formats can be added at the same time using an object:</p>
<pre><code>tv4.addFormat({
    &#39;my-format&#39;: function () {...},
    &#39;other-format&#39;: function () {...}
});</code></pre>
<h5 id="definekeyword-keyword-validationfunction-">defineKeyword(keyword, validationFunction)</h5>
<p>Add a custom keyword validator.</p>
<ul>
<li><code>keyword</code> is a string, corresponding to a schema keyword</li>
<li><code>validationFunction</code> is a function that either returns:<ul>
<li><code>null</code> (meaning no error)</li>
<li>an error string (explaining the reason for failure)</li>
<li>an error object (containing some of: <code>code</code>/<code>message</code>/<code>dataPath</code>/<code>schemaPath</code>)</li>
</ul>
</li>
</ul>
<pre><code>tv4.defineKeyword(&#39;my-custom-keyword&#39;, function (data, value, schema) {
    if (simpleFailure()) {
        return &quot;Failure&quot;;
    } else if (detailedFailure()) {
        return {code: tv4.errorCodes.MY_CUSTOM_CODE, message: {param1: &#39;a&#39;, param2: &#39;b&#39;}};
    } else {
        return null;
    }
});</code></pre>
<p><code>schema</code> is the schema upon which the keyword is defined.  In the above example, <code>value === schema[&#39;my-custom-keyword&#39;]</code>.</p>
<p>If an object is returned from the custom validator, and its <code>message</code> is a string, then that is used as the message result.  If <code>message</code> is an object, then that is used to populate the (localisable) error template.</p>
<h5 id="defineerror-codename-codenumber-defaultmessage-">defineError(codeName, codeNumber, defaultMessage)</h5>
<p>Defines a custom error code.</p>
<ul>
<li><code>codeName</code> is a string, all-caps underscore separated, e.g. <code>&quot;MY_CUSTOM_ERROR&quot;</code></li>
<li><code>codeNumber</code> is an integer &gt; 10000, which will be stored in <code>tv4.errorCodes</code> (e.g. <code>tv4.errorCodes.MY_CUSTOM_ERROR</code>)</li>
<li><code>defaultMessage</code> is an error message template to use (assuming translations have not been provided for this code)</li>
</ul>
<p>An example of <code>defaultMessage</code> might be: <code>&quot;Incorrect moon (expected {expected}, got {actual}&quot;</code>).  This is filled out if a custom keyword returns a object <code>message</code> (see above).  Translations will be used, if associated with the correct code name/number.</p>
<h2 id="demos">Demos</h2>
<h3 id="basic-usage">Basic usage</h3>
<div class="content inline-demo" markdown="1" data-demo="demo1">
<pre class="code" id="demo1">
var schema = {
    &quot;items&quot;: {
        &quot;type&quot;: &quot;boolean&quot;
    }
};
var data1 = [true, false];
var data2 = [true, 123];

alert(&quot;data 1: &quot; + tv4.validate(data1, schema)); // true
alert(&quot;data 2: &quot; + tv4.validate(data2, schema)); // false
alert(&quot;data 2 error: &quot; + JSON.stringify(tv4.error, null, 4));
</pre>
</div>

<h3 id="use-of-code-ref-code-">Use of <code>$ref</code></h3>
<div class="content inline-demo" markdown="1" data-demo="demo2">
<pre class="code" id="demo2">
var schema = {
    &quot;type&quot;: &quot;array&quot;,
    &quot;items&quot;: {&quot;$ref&quot;: &quot;#&quot;}
};
var data1 = [[], [[]]];
var data2 = [[], [true, []]];

alert(&quot;data 1: &quot; + tv4.validate(data1, schema)); // true
alert(&quot;data 2: &quot; + tv4.validate(data2, schema)); // false
</pre>
</div>

<h3 id="missing-schema">Missing schema</h3>
<div class="content inline-demo" markdown="1" data-demo="demo3">
<pre class="code" id="demo3">
var schema = {
    &quot;type&quot;: &quot;array&quot;,
    &quot;items&quot;: {&quot;$ref&quot;: &quot;<a href="http://example.com/schema">http://example.com/schema</a>&quot; }
};
var data = [1, 2, 3];

alert(&quot;Valid: &quot; + tv4.validate(data, schema)); // true
alert(&quot;Missing schemas: &quot; + JSON.stringify(tv4.missing));
</pre>
</div>

<h3 id="referencing-remote-schema">Referencing remote schema</h3>
<div class="content inline-demo" markdown="1" data-demo="demo4">
<pre class="code" id="demo4">
tv4.addSchema(&quot;<a href="http://example.com/schema">http://example.com/schema</a>&quot;, {
    &quot;definitions&quot;: {
        &quot;arrayItem&quot;: {&quot;type&quot;: &quot;boolean&quot;}
    }
});
var schema = {
    &quot;type&quot;: &quot;array&quot;,
    &quot;items&quot;: {&quot;$ref&quot;: &quot;<a href="http://example.com/schema#/definitions/arrayItem">http://example.com/schema#/definitions/arrayItem</a>&quot; }
};
var data1 = [true, false, true];
var data2 = [1, 2, 3];

alert(&quot;data 1: &quot; + tv4.validate(data1, schema)); // true
alert(&quot;data 2: &quot; + tv4.validate(data2, schema)); // false
</pre>
</div>

<h2 id="supported-platforms">Supported platforms</h2>
<ul>
<li>Node.js</li>
<li>All modern browsers</li>
<li>IE &gt;= 7</li>
</ul>
<h2 id="installation">Installation</h2>
<p>You can manually download <a href="https://raw.github.com/geraintluff/tv4/master/tv4.js"><code>tv4.js</code></a> or the minified <a href="https://raw.github.com/geraintluff/tv4/master/tv4.min.js"><code>tv4.min.js</code></a> and include it in your html to create the global <code>tv4</code> variable.</p>
<p>Alternately use it as a CommonJS module:</p>
<pre><code class="lang-js">var tv4 = require(&#39;tv4&#39;);</code></pre>
<p>or as an AMD module (e.g. with requirejs):</p>
<pre><code class="lang-js">require(&#39;tv4&#39;, function(tv4){
  //use tv4 here
});</code></pre>
<h4 id="npm">npm</h4>
<pre><code>$ npm install tv4</code></pre>
<h4 id="bower">bower</h4>
<pre><code>$ bower install tv4</code></pre>
<h4 id="component-io">component.io</h4>
<pre><code>$ component install geraintluff/tv4</code></pre>
<h2 id="build-and-test">Build and test</h2>
<p>You can rebuild and run the node and browser tests using node.js and <a href="http://http://gruntjs.com/">grunt</a>:</p>
<p>Make sure you have the global grunt cli command:</p>
<pre><code>$ npm install grunt-cli -g</code></pre>
<p>Clone the git repos, open a shell in the root folder and install the development dependencies:</p>
<pre><code>$ npm install</code></pre>
<p>Rebuild and run the tests:</p>
<pre><code>$ grunt</code></pre>
<p>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 <a href="http://geraintluff.github.io/tv4/test/index.html"><code>test/index.html</code></a> and <a href="http://geraintluff.github.io/tv4/test/index-min.html"><code>test/index-min.html</code></a>.</p>
<h2 id="contributing">Contributing</h2>
<p>Pull-requests for fixes and expansions are welcome. Edit the partial files in <code>/source</code> and add your tests in a suitable suite or folder under <code>/test/tests</code> and run <code>grunt</code> 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.</p>
<p>Do you speak another language? <code>tv4</code> needs internationalisation - please contribute language files to <code>/lang</code>!</p>
<h2 id="packages-using-tv4">Packages using tv4</h2>
<ul>
<li><a href="http://chaijs.com/plugins/chai-json-schema">chai-json-schema</a> is a <a href="http://chaijs.com">Chai Assertion Library</a> plugin to assert values against json-schema.</li>
<li><a href="http://www.github.com/Bartvds/grunt-tv4">grunt-tv4</a> is a plugin for <a href="http://http://gruntjs.com/">Grunt</a> that uses tv4 to bulk validate json files.</li>
</ul>
<h2 id="license">License</h2>
<p>The code is available as &quot;public domain&quot;, meaning that it is completely free to use, without any restrictions at all.  Read the full license <a href="http://geraintluff.github.com/tv4/LICENSE.txt">here</a>.</p>
<p>It&#39;s also available under an <a href="http://jsonary.com/LICENSE.txt">MIT license</a>.</p>

</div>
</body>
</html>