Skip to content

Instantly share code, notes, and snippets.

@pixyj
Last active December 14, 2015 23:49
Show Gist options
  • Save pixyj/5168625 to your computer and use it in GitHub Desktop.
Save pixyj/5168625 to your computer and use it in GitHub Desktop.
Check if a javascript object(instance) has the same properties of the same type with respect to a known object(schema).
/*******************************************************************************************************
Checks if an object(instance) has the same properties of the same type with respect to a known
object(schema).
validate is especially useful to test whether the server side code sends JSON as expected by the client
Usage Example:
1. Create a sample expected object (sampleSchema).
2. When data(sampleInstance) is received, call validate(sampleSchema, sampleInstance)
3. validate returns 0 if no errors are found, else logs errors (Property not found/Type Mismatch) and
returns error count.
sampleSchema = {
"name": "nelly furtado",
"age": 34,
"albums": ["folklore", "loose"],
"details": {
"genres": ["pop", "latin", "hip-hop"]
}
}
sampleInstance = {
"name": "shakira",
"age": 32,
"albums": ["one", 2],
"details": {
"genres": ["pop", "latin"]
}
}
> validate(sampleSchema, sampleInstance)
Type Mismatch ["folklore", 2]
> 1
> validate(sampleSchema, sampleSchema)
> 0
*******************************************************************************************************/
validate = function(schema, instance) {
var errors = 0;
var i, j, arrLength, zeroSchema, zeroInstance;
var getType = function(attr) {
return Object.prototype.toString.call(attr);
};
var addError = function(msg, attrs) {
console.error(msg, attrs);
errors += 1;
};
var validateArray = function(schemaArr, instanceArr) {
//Each element of instance array is compared with zeroth element of schema array
//All elements of instance array MUST be of same type for no errors to occur
var zeroSchema = schemaArr[0];
var zeroInstance = instanceArr[0];
if(zeroInstance === undefined) {
return 0;
}
var j, arrLength = instanceArr.length;
for(j=0; j<arrLength; j += 1) {
errors += validate(zeroSchema, instanceArr[j]);
}
};
if( getType(schema) !== getType(instance) ) {
addError("Type Mismatch", [schema, instance]);
}
else if( getType(schema) == getType("") ) {
//Everything ok if both schema and instance types are strings
}
else if( getType(schema) === getType([]) ) {
validateArray(schema, instance);
}
else {
for(i in schema) {
if(schema.hasOwnProperty(i)) {
if(!instance.hasOwnProperty(i)) {
addError("Property Not found", i);
}
//Special Handling for arrays
else if( getType(schema[i]) === getType([]) ) {
validateArray(schema[i], instance[i])
}
//Special Handling for nested objects
else if( getType(schema[i]) === getType({}) ) {
errors += validate(schema[i], instance[i]);
}
}
}
}
return errors;
}
@pixyj
Copy link
Author

pixyj commented Mar 15, 2013

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