vue驗證中如何使用策略模式

根據網上現有的資料改的vue適用的策略驗證,若是還須要別的驗證直接本身添加規則就好了 。 上代碼
新建一個js文件vue

let strategys = {
    isNotEmpty: (value, errorMsg) => {
        if(value === ''){
            return errorMsg;
        }
    },
    minLength: (value, length, errorMsg) => {
        if(value.length < length){
            return errorMsg;
        }
    },
    mobileFormat: (value, errorMsg) => {
        if(!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
            return errorMsg;
        }
    }
}

export var Validator = function () {
        this.cache = [];  // 保存效驗規則
};
Validator.prototype.add = function(dom,rule,errorMsg) {
    var str = rule.split(":");
    this.cache.push(function(){
        // str 返回的是 minLength:6 
        var strategy = str.shift();
        str.unshift(dom); // value添加進參數列表
        str.push(errorMsg);  // 把errorMsg添加進參數列表
        return strategys[strategy].apply(dom,str);
    });
};
Validator.prototype.start = function () {
  for (var i = 0, validatorFunc; validatorFunc = this.cache[i++]; ) {
        var msg = validatorFunc()  // 開始效驗 並取得效驗後的返回信息
        if(msg) {
            return msg
        }
    }
};

將文件導入要使用的組件或者視圖中app

import { Validator } from './validate.js'

而後在你須要的地方導入就搞定了dom

methods: {
            submit_click() {
                let errorMsg = this.validateFunc();
                if (errorMsg) {
                    alert(errorMsg);
                    return false
                }
            },
            validateFunc() {
              let that = this;
                let validator = new Validator();
                validator.add(that.userName, 'isNotEmpty', '用戶名不能爲空');
                validator.add(that.password, 'minLength:6', '密碼長度不能小於6位');
                validator.add(that.phoneNumber, 'mobileFormat', '手機號碼格式不正確');

                var errorMsg = validator.start(); // 得到效驗結果
                return errorMsg; // 返回效驗結果
            }
        }
相關文章
相關標籤/搜索