- 第一步我们要把这些校验逻辑都封装成策略对象:
//策略对象 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 } }