策略模式下的校验对象

可以理解为设计模式当中的策略模式。

对于多条件问题都可以应用策略模式来解决。

// 验证类别对象不断添加
let typeObj = {
  isNull: function (str) {
    if (!str || str.length <= 0) {
      return true
    }
    return false
  },
  isVar: function (str) {
    let reg = /[0-9a-z|_]+/g
    if (reg.test(str)) {
      return true
    }
    return false
  },
  isBlank: function (str) {
    let reg = /s+/g
    if (reg.test(str)) {
      return true
    }
    return false
  },
  isPath: function (str) {
    let reg = /^/([0-9a-zA-Z|_]+/?)*$/g
    if (!reg.test(str)) {
      return true
    }
    return false
  },
  isDomain:function(str){
    let reg = /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/
    if (!reg.test(str)) {
      return true
    }
    return false
  },
  isIp:function(str){
    let reg =/^(d{1,2}|1dd|2[0-4]d|25[0-5])(.(d{1,2}|1dd|2[0-4]d|25[0-5])){3}$/

    if (!reg.test(str)) {
      return true
    }
    return false
  },
  isNumber:function(str){
    let reg =/^[1-9][0-9]*$/g

    if (!reg.test(str)) {
      return true
    }
    return false
  }
}

function validate () {
  this.validateArr = []
}
// type是验证类别,variable是变量,tip是提示内容
validate.prototype.add = function (type, variable, tip) {
  this.validateArr.push(() => {
    if (typeObj[type](variable)) {
      return tip
    }
  })
}
validate.prototype.map = function () {
  for (let i = 0, fn; fn = this.validateArr[i++];) {
    if (fn()) {
      return fn()
    }
  }
}

  

原文地址:https://www.cnblogs.com/zhensg123/p/10614407.html