策略模式在运行时选择算法,其中一个例子就是用来解决表单验证的问题,通过创建一个validate()方法的验证器(validator)对象。
无论表单的具体类型是什么,该方法都将会被调用,并且总是返回相同的结果,一个未经验证的数据列表以及错误消息
var validator = {
// 所有可用的检查
types : {},
// 当前会话中的错误消息
errors : {},
// 当前验证配置
// 名称:验证类型
config : {},
// 接口方法
// data :键值对
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: "validattionError",
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.hasErrors.length !== 0;
}
};
validator.types.isNonEmpty = {
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, e.g. 1,3,14 or 2014"
};
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 data = {
first_name : "Super",
last_name : "Man",
age : "unknown",
username : "o_O"
};
validator.config = {
first_name : "isNonEmpty",
age : "isNumber",
username : "isAlphaNum"
};
validator.validate(data);
if(validator.hasErrors()) {
console.log(validator.messages.join("\n"));
}