1 | // Provides support for asynchronous validation (fetching schemas) using jQuery |
---|
2 | // Callback is optional third argument to tv4.validate() - if not present, synchronous operation |
---|
3 | // callback(result, error); |
---|
4 | if (typeof (tv4.asyncValidate) === 'undefined') { |
---|
5 | tv4.syncValidate = tv4.validate; |
---|
6 | tv4.validate = function (data, schema, callback, checkRecursive) { |
---|
7 | if (typeof (callback) === 'undefined') { |
---|
8 | return this.syncValidate(data, schema, checkRecursive); |
---|
9 | } else { |
---|
10 | return this.asyncValidate(data, schema, callback, checkRecursive); |
---|
11 | } |
---|
12 | }; |
---|
13 | tv4.asyncValidate = function (data, schema, callback, checkRecursive) { |
---|
14 | var $ = jQuery; |
---|
15 | var result = tv4.validate(data, schema, checkRecursive); |
---|
16 | if (!tv4.missing.length) { |
---|
17 | callback(result, tv4.error); |
---|
18 | } else { |
---|
19 | // Make a request for each missing schema |
---|
20 | var missingSchemas = $.map(tv4.missing, function (schemaUri) { |
---|
21 | return $.getJSON(schemaUri).success(function (fetchedSchema) { |
---|
22 | tv4.addSchema(schemaUri, fetchedSchema); |
---|
23 | }).error(function () { |
---|
24 | // If there's an error, just use an empty schema |
---|
25 | tv4.addSchema(schemaUri, {}); |
---|
26 | }); |
---|
27 | }); |
---|
28 | // When all requests done, try again |
---|
29 | $.when.apply($, missingSchemas).done(function () { |
---|
30 | var result = tv4.asyncValidate(data, schema, callback, checkRecursive); |
---|
31 | }); |
---|
32 | } |
---|
33 | }; |
---|
34 | } |
---|