Skip to content

Instantly share code, notes, and snippets.

@winniehell
Last active August 29, 2015 14:23
Show Gist options
  • Save winniehell/a2dc462a64aff470268d to your computer and use it in GitHub Desktop.
Save winniehell/a2dc462a64aff470268d to your computer and use it in GitHub Desktop.
var jsen = require('jsen');
function validateAndOutput(schema, title, data) {
var validate = jsen(schema);
var result = validate(data);
if (result) {
console.log('Valid: ' + title + ' = ' + JSON.stringify(data));
} else {
console.log('Invalid: ' + title + ' = ' + JSON.stringify(data));
console.log('Errors: ' + JSON.stringify(validate.errors));
}
console.log();
}
var mySchema = {
id: 'http://example.com/schema#',
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string'
},
friends: {
$ref: 'http://example.com/schema#'
}
},
required: ['name']
}
};
validateAndOutput(
{'$ref': 'http://json-schema.org/draft-04/schema#'},
'mySchema',
mySchema
);
var myInvalidData = [
{
name: 'Mario',
friends: [
{
name: 'Luigi',
friends: []
},
{
Wario: 'broken!'
}
]
}
];
validateAndOutput(
mySchema,
'myInvalidData',
myInvalidData
);
var luigi = myInvalidData[0].friends[0];
console.log('Remove ' + luigi.name + "'s non-existent friends");
luigi.friends = undefined;
validateAndOutput(
mySchema,
'myInvalidData (reduced)',
myInvalidData
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment