Created
November 4, 2014 23:48
-
-
Save AubreyHewes/c6cea1665dd66d41695a to your computer and use it in GitHub Desktop.
JSONSchema-Validation-JJV-PoC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jshint strict: false, -W116: false, -W098: false */ | |
/*global jjv*/ | |
/** | |
* JJV Validation + own stuff (non production) .. uses jquery due to JSONEditor not exposing libraries | |
*/ | |
JSONEditor.Validator.JJV = JSONEditor.Validator.extend({ | |
_validateSchema: function (schema, value, path) { | |
var me = this, errors = [], valid, i, j; | |
path = path || 'root'; | |
// Work on a copy of the schema | |
schema = $.extend({}, this.jsoneditor.expandRefs(schema)); | |
// validate using JJV | |
var results = jjv().validate(schema, value, { useDefault: true }); | |
if (results.validation) { | |
// results.validation is according to schema structure/json-editor wants an array of errors.. | |
// so now comes a load of crap... | |
$('form').find('[data-schemapath="root"]').find('input,select,textarea').each(function (idx, field) { | |
var fieldPath = ((field.name.substr(0, 5) === 'root[') ? | |
field.name.substr(5, (field.name.length - 6)) : | |
field.name); | |
var property = me.isValid(fieldPath.split(']['), results.validation); | |
if (typeof property === 'object') { | |
$.each(property, function (name, value) { | |
errors.push({ | |
path: 'root.' + fieldPath.split('][').join('.'), | |
property: name, | |
message: me.translate('error_' + name) | |
}); | |
}); | |
} | |
}); | |
} | |
// Custom type validation | |
$.each(JSONEditor.defaults.custom_validators, function (i, validator) { | |
errors = errors.concat(validator(schema, value, path)); | |
}); | |
return errors; | |
}, | |
isValid: function (pathNibbles, errors) { | |
var me = this, nibble = pathNibbles.shift(); | |
if (errors[nibble]) { | |
if (errors[nibble].schema) { | |
return me.isValid(pathNibbles, errors[nibble].schema); | |
} | |
return errors[nibble]; | |
} | |
return true; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment