1. 程式人生 > >理解javascript中的策略模式

理解javascript中的策略模式

// 策略物件
var strategys = {
    isNotEmpty: function(value,errorMsg) {
        if(value === '') {
            return errorMsg;
        }
    },
    // 限制最小長度
    minLength: function(value,length,errorMsg) {
        if(value.length < length) {
            return errorMsg;
        }
    },
    
// 手機號碼格式 mobileFormat: function(value,errorMsg) { if(!/(^1[3|5|8][0-9]{9}$)/.test(value)) { return errorMsg; } } }; var Validator = function(){ this.cache = []; // 儲存效驗規則 }; Validator.prototype.add = function(dom,rules) { var self = this; for(var
i = 0, rule; rule = rules[i++]; ){ (function(rule){ var strategyAry = rule.strategy.split(":"); var errorMsg = rule.errorMsg; self.cache.push(function(){ var strategy = strategyAry.shift(); strategyAry.unshift(dom.value); strategyAry.push(errorMsg);
return strategys[strategy].apply(dom,strategyAry); }); })(rule); } }; Validator.prototype.start = function(){ for(var i = 0, validatorFunc; validatorFunc = this.cache[i++]; ) { var msg = validatorFunc(); // 開始效驗 並取得效驗後的返回資訊 if(msg) { return msg; } } }; // 程式碼呼叫 var registerForm = document.getElementById("registerForm"); var validateFunc = function(){ var validator = new Validator(); // 建立一個Validator物件 /* 新增一些效驗規則 */ validator.add(registerForm.userName,[ {strategy: 'isNotEmpty',errorMsg:'使用者名稱不能為空'}, {strategy: 'minLength:6',errorMsg:'使用者名稱長度不能小於6位'} ]); validator.add(registerForm.password,[ {strategy: 'minLength:6',errorMsg:'密碼長度不能小於6位'}, ]); validator.add(registerForm.phoneNumber,[ {strategy: 'mobileFormat',errorMsg:'手機號格式不正確'}, ]); var errorMsg = validator.start(); // 獲得效驗結果 return errorMsg; // 返回效驗結果 }; // 點選確定提交 registerForm.onsubmit = function(){ var errorMsg = validateFunc(); if(errorMsg){ alert(errorMsg); return false; } }

相關推薦

no