JavaScript设计模式 - 策略模式(表单验证)

表单提交的时候,总是要校验,不同的表单可能校验相同的功能。
为了避免代码重复的复制黏贴,使用策略模式,写出来的代码赏心悦目,且可扩展,还可以作为插件到处使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>策略模式_表单验证</title>
</head>
<body>
    <form id="registerFrom" method="post" action="">
        请输入用户名: <input type="text" name="userName" /> <br/>
        请输入密码: <input type="text" name="password" /> <br/>
        请输入手机号码: <input type="text" name="phoneNumber" /> <br/>
        <button>提交</button>
    </form>
    <script>
        

        // 对象字面量
        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[7|3|5|8][0-9]{9}$)/.test(value)) {
                    return errorMsg;
                };
            },

            isSpace: function(value, errorMsg) {
                if([...value].every( item => {
                    return item === ' ';
                })) {
                    return errorMsg;
                };
            }
        };



        // 校验表单类
        var Validator = function() {
            this.catch = [];
        };

        Object.assign(Validator.prototype, {

            add: function(dom, rules, errorMsg) {
                var _self = this;
                for (var i = 0, rule; rule = rules[i ++]; ) {
                    (function(rule) {
                        var ary = rule.strategy.split(':');
                        _self.catch.push(function() {
                            var strategy = ary.shift();
                            ary.unshift(dom.value);
                            ary.push(rule.errorMsg);
                            return strategies[strategy].apply(dom, ary);
                        });
                    })(rule);
                };
            },

            start: function() {
                for (var i = 0, validatorFunc; validatorFunc = this.catch[i ++]; ) {
                    var msg = validatorFunc();
                    if (msg) {
                        return msg;
                    };
                };
            }
        });


        // test

        // 校验方法封装
        var validataFunc = function() {
            var validator = new Validator();

            validator.add(registerFrom.userName, [{
                strategy: 'isSpace',
                errorMsg: '用户名不能全为空!'
            },{
                strategy: 'minLength:10',
                errorMsg: '用户名长度不能少于10个字符!'
            }]);
            validator.add(registerFrom.password, [{
                strategy: 'isSpace',
                errorMsg: '密码不能全为空!'
            },{
                strategy: 'minLength:6',
                errorMsg: '密码长度不能小于6个字符!'
            }]);
            validator.add(registerFrom.phoneNumber, [{
                strategy: 'isMobile',
                errorMsg: '手机号码格式不对!'
            }]);

            var errMsg = validator.start();
            return errMsg;
        };
        
        var registerFrom = document.querySelector('#registerFrom')
        registerFrom.onsubmit = function() {
            var errorMsg = validataFunc();
            if (errorMsg) {
                console.log(errorMsg);
                return false;
            };
        };
    </script>
</body>
</html>

 

使用对象字面量和闭包和apply来实现策略模式的,很不错

posted @ 2017-07-18 19:32  Sorrow.X  阅读(529)  评论(0编辑  收藏  举报