4-策略模式-表單驗證

<!DOCTYPE html>
<html lang='en'>

<head>
    <meat charset='UTF-8'>
        <meat name='viewport' content='width=device-width, initial-scale=1.0'>
            <style>
                span {
                    color: red;
                }
            </style>
</head>

<body>
    <div id="show">
        <div>
            賬號:<input type="text" name="" id="userName">
            <span id='showName'></span>
        </div>
        <div>
            密碼:<input type="text" name="" id="pas">
            <span id='showPas'></span>
        </div>
        <div>
            郵箱:<input type="text" name="" id="emDOm">
            <span id='showEm'></span>
        </div>
    </div>
    <button type="submit" id='sub'>提交</button>

    <script>
        /**
         * 1.表單驗證規則
         * 2.定義原始規則
         * 3.自定義添加原始規則
         * 4.開始執行規則驗證
         * 5.繼承表單驗證規則
        */
        // 表單驗證規則
        function Validator() {
            this.cache = []; // 存儲需要驗證的規則
            this.warning = []; // 存儲展示警告信息的DOM
        }
        // 定義原始規則
        Validator.prototype.strategies = {
            isNotEmpty: function (value, errorText) {
                if (value != '') {
                    return true;
                } else {
                    return errorText
                }
            },
            minLength: function (value, length, errorText) {
                if (value != '' && value.length < length) {
                    return errorText
                } else {
                    return true;
                }
            },
            maxLength: function (value, length, errorText) {
                if (value != '' && value.length > length) {
                    return errorText
                } else {
                    return true;
                }
            },
        }
        // 添加要驗證的規則
        Validator.prototype.add = function (dom, showDom, strategyArr) {
            let self = this;
            self.warning.push(showDom); // 將展示警告信息的DOM保存起來
            strategyArr.forEach((ele, index) => {
                self.cache.push(function () {
                    let arr = ele.strategy.split(':');
                    let type = arr.shift();
                    arr.push(ele.errorText)
                    let msg = self.strategies[type].apply(this, [dom.value, ...arr])

                    if (msg != true) {
                        showDom.innerText = msg;
                        msg = false;
                    }
                    return msg
                })
            })
        }

        // 開始驗證規則
        Validator.prototype.start = function () {
            let flag = true;
            this.warning.forEach((item) => {
                item.innerText = '';
            })
            this.cache.forEach((item) => {
                if (item() != true) {
                    flag = false;
                }
            })
            this.cache = [];
            return flag;
        }

        // 添加自定義校驗規則   
        Validator.prototype.extend = function(config) {
            for(let type in config) {
                Validator.prototype.strategies[type] = config[type]
            }
        }


        let validattor = new Validator();
        // 添加新的郵箱驗證規則
        validattor.extend({
            isEmail: function(value, errorText) {
                if(value && value.indexOf('@') != -1) {
                    return true
                }else {
                    return errorText
                }
            }
        })

        // 代理
        let ProxyValid = (function () {
            // 添加驗證規則
            validattor.add(userName, showName, [
                {
                    strategy: 'minLength:2',
                    errorText: '長度不能小於2位'
                },
                {
                    strategy: 'isNotEmpty',
                    errorText: '賬號不能爲空'
                },
                {
                    strategy: 'maxLength:6',
                    errorText: '長度不能超過6位'
                },
            ]);
            validattor.add(pas, showPas, [
                {
                    strategy: 'isNotEmpty',
                    errorText: '密碼不能爲空'
                },
                {
                    strategy: 'minLength:2',
                    errorText: '長度不能小於2位'
                },
                {
                    strategy: 'maxLength:6',
                    errorText: '長度不能超過6位'
                },
            ]);
          
            validattor.add(emDOm, showEm, [
                {
                    strategy: 'isEmail',
                    errorText: '必選含有@字符'
                }
            ])
            // 執行規則
            return function () {
                if (validattor.start()) {
                    alert('驗證通過');
                }
            }
        })

        sub.onclick = function () {
            let a = ProxyValid();
            a()
        }
    </script>
</body>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章