Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript 设计模式(策略模式) #45

Open
wl05 opened this issue Jun 14, 2019 · 0 comments
Open

javascript 设计模式(策略模式) #45

wl05 opened this issue Jun 14, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented Jun 14, 2019

概念

定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。

实现

在表单验证中我们通常需要使用不同的规则校验不同的表单字段。

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

        }
    }
}

var validataFunc = function () {
    var validator = new Validator()
    // 创建一个 validator 对象
    /***************添加一些校验规则****************/
    validator.add(registerForm.userName, 'isNonEmpty', '用户名不能为空')

    validator.add(registerForm.password, 'minLength:6', '密码长度不能少于 6 位')

    validator.add(registerForm.phoneNumber, 'isMobile', '手机号码格式不正确')

    var errorMsg = validator.start()
    // 获得校验结果
    return errorMsg
    // 返回校验结果
}
var registerForm = document.getElementById('registerForm')

registerForm.onsubmit = function () {
    var errorMsg = validataFunc()
    // 如果 errorMsg 有确切的返回值,说明未通过校验
    if (errorMsg) {
        alert(errorMsg)

        return false
        // 阻止表单提交
    }
}

var Validator = function () {
    this.cache = []
    // 保存校验规则
}

Validator.prototype.add = function (dom, rule, errorMsg) {
    var ary = rule.split(':')
    // 把 strategy 和参数分开
    this.cache.push(function () { // 把校验的步骤用空函数包装起来,并且放入 cache 
        var strategy = ary.shift()
        // 用户挑选的 strategy 
        ary.unshift(dom.value)
        // 把 input 的 value 添加进参数列表
        ary.push(errorMsg)
        // 把 errorMsg 添加进参数列表
        return strategies[strategy].apply(dom, ary)

    })

}

Validator.prototype.start = function () {
    for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
        var msg = validatorFunc()
        // 开始校验,并取得校验后的返回信息
        if (msg) { // 如果有确切的返回值,说明校验没有通过
            return msg
        }
    }
}

参考资料

  1. JavaScript设计模式与开发实践-第五章-策略模式
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant