策略模式設計表單校驗
- 第一步我們要把這些校驗邏輯都封裝成策略對象:
//策略對象 var strategies = { isNonEmpty: function (value, errorMsg) { if (value === '') { return errorMsg } }, minLength: function (value, length, errorMsg) { if (value.length < length) { return errorMsg } }, isMobile: function (value, errorMsg) { if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) { return errorMsg } } }
- 接下來我們準備實現Validator類,validator類在這裏作為context,負責接收用戶的請求,並委托給strategy對象。在給出Validator類的代碼之前,有必要提前了解用戶是如何向Validator類發送請求的,代碼如下
var form = document.getElementById('registerForm'); var btn = document.getElementById('submit'); btn.onclick = function(){ console.log(form.userName.value) var validator = new Validator(); validator.add(form.userName, [ {strategy: 'isNonEmpty', errorMsg: '用戶名不能為空'}, {strategy: 'minLength:6', errorMsg: '用戶名長度不能小於6'} ]) validator.add(form.password, [ {strategy: 'minLength:6', errorMsg: '密碼長度不能小於6'} ]) validator.add(form.phoneNumber, [ {strategy: 'isMobile', errorMsg: '手機號格式不正確'} ]) var error = validator.start(); if (error) { alert(error) } return false }
- Validator類的實現
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 strategyArr = rule.strategy.split(':'); var errorMsg = rule.errorMsg self.cache.push(function () { var strategy = strategyArr.shift() strategyArr.unshift(dom.value) strategyArr.push(errorMsg) return strategies[strategy].apply(self, strategyArr) }) })(rule) } } Validator.prototype.start = function () { for (var i = 0, fun; fun = this.cache[i++];) { var errorMsg = fun() if (errorMsg) return errorMsg } }
最後更新:2017-11-17 15:05:19