liujsim / blog

blog
https://github.com/liujsim/blog/issues
MIT License
1 stars 0 forks source link

简单的表单验证工具类 #9

Open liujsim opened 6 years ago

liujsim commented 6 years ago

初衷:为目前做的小程序项目写一个基础的表单验证工具类

const strategies = {
  isNoEmpty (value, errorMsg) {
    if (value === '') {
      return errorMsg
    }
  },
  isMobile (value, errorMsg) {
    let pattern = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
    if (!pattern.test(value)) {
      return errorMsg
    }
  },
  isSmsCode (value, errorMsg) {
    let pattern = /^\d{6,}$/
    if (!pattern.test(value)) {
      return errorMsg
    }
  }
}

class Validation {
  constructor (strategies) {
    this.strategies = strategies
    this.validateFns = []
  }

  /**
   *  useage: validation.add(form.username, 'isNoEmpty', '用户名不能为空');
   * @param ref   待校验的值
   * @param rule  策略名称,strategies key
   * @param errorMsg  错误消息
   */
  add (ref, rule, errorMsg) {
    let fn = this.strategies[rule].bind(null, ref, errorMsg)
    this.validateFns.push(fn)
  }
  start () {
    for (let element of this.validateFns) {
      let msg = element()
      if (msg) {
        return msg
      }
    }
  }
}

export const validation = new Validation(strategies)
liujsim commented 6 years ago

参考: 策略模式在表单验证中的应用

liujsim commented 6 years ago

usage

let phoneValidation = new Validation(strategies)

phoneValidation.add('199', 'isNoEmpty', '不能为空')
phoneValidation.add('199', 'isMobile', '请输入正确的手机号')

let phoneMsg = phoneValidation.start()