Skip to content

Instantly share code, notes, and snippets.

@Sljubura
Created March 12, 2013 21:44
Show Gist options
  • Save Sljubura/5147365 to your computer and use it in GitHub Desktop.
Save Sljubura/5147365 to your computer and use it in GitHub Desktop.
Strategy pattern
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