Last active
August 29, 2015 14:24
-
-
Save ArtskydJ/140edea3b07566c2aa54 to your computer and use it in GitHub Desktop.
The typeof validator
This file contains 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
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
commented
Jul 10, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment