Skip to content

Instantly share code, notes, and snippets.

@ArtskydJ
Last active August 29, 2015 14:24
Show Gist options
  • Save ArtskydJ/140edea3b07566c2aa54 to your computer and use it in GitHub Desktop.
Save ArtskydJ/140edea3b07566c2aa54 to your computer and use it in GitHub Desktop.
The typeof validator
var myAwesomeSchema = {
hello: 'string',
world: {
thing: 'number',
lol: 'boolean'
},
another: [
{ a: 'number', b: 'number' },
{ c: 'number', d: 'number' }
]
}
var goodDoc = {
hello: 'very yes',
world: {
thing: 37,
lol: true
},
another: [
{ a: 209, b: 3 },
{ c: 94, d: 46 }
]
}
var badDoc = {
hello: 'very yes',
world: {
thing: 37,
lol: 'not boolean haha'
}
}
function validator(schema, document) {
return Object.keys(schema).every(function (key) {
return (typeof schema[key] === 'object') ?
validator(schema[key], document[key]) :
schema[key] === typeof document[key]
})
}
document.write(validator(myAwesomeSchema, goodDoc)) // => true
document.write(validator(myAwesomeSchema, badDoc)) // => false
@saibotsivad
Copy link

var myAwesomeSchema = {
  hello: 'string',
  world: {
    things: 'function',
    stuff: 'number'
  }
}

@ArtskydJ
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment