Skip to content

Instantly share code, notes, and snippets.

@Gwash3189
Created May 8, 2014 04:19
Show Gist options
  • Save Gwash3189/b1d3b6cf7bdfdea50c84 to your computer and use it in GitHub Desktop.
Save Gwash3189/b1d3b6cf7bdfdea50c84 to your computer and use it in GitHub Desktop.
Recursive object Validation in TS
module PowerLine {
export interface IValidatable {
Validate: (model: any, info: any) => boolean;
}
export class Validator implements IValidatable {
public Validate(info: any) {
var results = [];
for (var key in info) {
if(key !== "constructor" && typeof info[key] !== "function"){
if(this.hasOwnProperty(key)){
results.push(this.Evaluate(info, key));
} else {
results.push(false);
}
}
}
if(results.indexOf(false) > -1){
return false;
}
return true;
}
private Evaluate(objectToCompare, toComparekey){
if(objectToCompare[toComparekey] instanceof Array && this[toComparekey] instanceof Array){
return true;
}
if(typeof this[toComparekey] === "object" && typeof objectToCompare[toComparekey] === "object"){
return this.Validate.call(this[toComparekey], objectToCompare[toComparekey]);
}
if(typeof this[toComparekey] === typeof objectToCompare[toComparekey]){
return true;
}
return false;
}
}
}
class Model extends PowerLine.Validator {
public Name: string = "";
public Age: number = 0;
public Todo: Array<any> = new Array<any>();
constructor() {
super();
}
}
class Test extends PowerLine.Validator {
public nestedObj = new Model();
constructor() {
super();
}
}
//Tests
var a = new Model();
var t = new Test();
setTimeout(function() {
console.assert(a.Validate({ Name: "", Age: 12, Todo: [] })); // the same as each other
console.assert(a.Validate({ Name: 12, Age: "32" , Todo: []}) === false); //not the same
console.assert(a.Validate({ Name: 12, Age: "32", Stuff: [] }) === false); //not the same
debugger;
console.assert(t.Validate(new Test())); //nested objects test. Should evaluate to true as test & the object being passed in are the same
console.assert(t.Validate({nestedObj: {Name: 12}}) === false); // should evaluate to false as the object being passed in is NOT the same
}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment