javascript篇:策略模式驗證表單

策略模式在運行時選擇算法,其中一個例子就是用來解決表單驗證的問題,經過建立一個validate()方法的驗證器(validator)對象。javascript

不管表單的具體類型是什麼,該方法都將會被調用,而且老是返回相同的結果,一個未經驗證的數據列表以及錯誤消息java

 

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"));
}
相關文章
相關標籤/搜索