I wrote a simple JSON schema validator. The full code is over here on gist.github.com However, the code without comment is...
validate = function(schema, instance) {
var i;
var errors = 0;
var getType = function(attr) {
return Object.prototype.toString.call(attr);
}
var addError = function(msg, attrs) {
console.error(msg, attrs);
errors += 1;
}
if(getType(schema) !== getType(instance)) {
addError("Type Mismatch", [schema, instance]);
return errors;
}
for(i in schema) {
if(schema.hasOwnProperty(i)) {
if(instance[i] == undefined) {
addError("Property Not found", i);
}
//Special Handling for arrays
else if( getType(schema[i]) === getType([]) ) {
var zeroSchema = schema[i][0];
var zeroInstance = instance[i][0];
if(zeroInstance === undefined) {
continue;
}
for(var j=0;j<instance[i].length;j++) {
errors += validate(zeroSchema, instance[i][j]);
}
}
//Special Handling for nested objects
else if( getType(schema[i]) === getType({}) ) {
errors += validate(schema[i], instance[i]);
}
}
}
return errors;
}
The code doesn't need the schema object to explicitly specify the type of object properties unlike the official one
I'm fairly new to javascript. How do I improve the code?