Created
March 12, 2013 21:44
-
-
Save Sljubura/5147365 to your computer and use it in GitHub Desktop.
Strategy pattern
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 data = { | |
first_name: "Vladimir", | |
last_name: "Sljubura", | |
age: "unknown", | |
username: "Slju" | |
}; | |
validator.config = { | |
first_name: 'required', | |
age: 'numeric', | |
username: 'alpha' | |
}; | |
validator.validate(data); | |
if (validator.hasErrors()) { | |
console.log(validator.messages.join("\n")); | |
} | |
validator.types.inNonEmpty = { | |
validate: function (value) { | |
return value !== ""; | |
}, | |
instructions: "the value cannot be empty" | |
}; | |
validator.types.isNumber = { | |
validate: function (value) { | |
return !isNaN(value); | |
}, | |
instructions: "the value can only be a valid number" | |
}; | |
validator.types.isAlphaNum = { | |
validate: function (value) { | |
return !/[^a-z0-9]/i.test(value); | |
}, | |
instructions: "the value can only contain characters and numbers, no special symbols" | |
}; | |
var validator = { | |
types: {}, | |
messages: {}, | |
config: {}, | |
validate: function (data) { | |
var i, msg, type, checker, result_ok; | |
this.messages = []; | |
for (i in data) { | |
if (data.hasOwnProperty(i)) { | |
type = this.config[i]; | |
checker = this.types[type]; | |
if (!type) { | |
continue; | |
} | |
if (!checker) { | |
throw { | |
name: "ValidationError", | |
message: "No handler to validate type " + type | |
}; | |
} | |
result_ok = checker.validate(data[i]); | |
if (!result_ok) { | |
msg = "Invalid value for *" + i + "*, " + checker.instructions; | |
this.messages.push(msg); | |
} | |
} | |
} | |
return this.hasErrors(); | |
}, | |
hasErrors: function () { | |
return this.messages.length !== 0; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment