[484] | 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; |
---|
[487] | 6 | tv4.validate = function (data, schema, callback, checkRecursive, banUnknownProperties) { |
---|
[484] | 7 | if (typeof (callback) === 'undefined') { |
---|
[487] | 8 | return this.syncValidate(data, schema, checkRecursive, banUnknownProperties); |
---|
[484] | 9 | } else { |
---|
[487] | 10 | return this.asyncValidate(data, schema, callback, checkRecursive, banUnknownProperties); |
---|
[484] | 11 | } |
---|
| 12 | }; |
---|
[487] | 13 | tv4.asyncValidate = function (data, schema, callback, checkRecursive, banUnknownProperties) { |
---|
[484] | 14 | var $ = jQuery; |
---|
[487] | 15 | var result = tv4.validate(data, schema, checkRecursive, banUnknownProperties); |
---|
[484] | 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 () { |
---|
[487] | 30 | var result = tv4.asyncValidate(data, schema, callback, checkRecursive, banUnknownProperties); |
---|
[484] | 31 | }); |
---|
| 32 | } |
---|
| 33 | }; |
---|
| 34 | } |
---|