微信小程序表單驗(yàn)證工具類(lèi)

前言

我們?cè)僭谛〕绦蚪?jīng)常使用表單驗(yàn)證功能,但是如果重復(fù)書(shū)寫(xiě)相同的驗(yàn)證代碼會(huì)很麻煩,所以我們可以封裝一個(gè)驗(yàn)證類(lèi)。

validate.js

const numberReg = /^-?[1-9][0-9]?.?[0-9]*$/    //數(shù)字正則
const phoneReg = /^1[0-9]{10,10}$/  //手機(jī)號(hào)正則

// 策略對(duì)象
let strategys = new Map([
  //判斷是否為空
  ['isEmpty', (value, errorMsg) => {
    if (value === '') {
      return errorMsg;
    }
  }],
  // 限制最小長(zhǎng)度
  ['minLength', (value, length, errorMsg) => {
    if (value.length < length) {
      return errorMsg;
    }
  }],
  // 限制最大長(zhǎng)度
  ['maxLength', (value, length, errorMsg) => {
    if (value.length > length) {
      return errorMsg;
    }
  }],
  // 手機(jī)號(hào)碼格式
  ['phone', (value, errorMsg) => {
    if (!phoneReg.test(value)) {
      return errorMsg;
    }
  }],
  //判斷數(shù)字
  ['number', (value, errorMsg) => {
    if (!numberReg.test(value)) {
      return errorMsg;
    }
  }]
])

class Validator {
  constructor() {
    this.cache = []; //保存校驗(yàn)規(guī)則
  }

  addRule(data, rules) {
    var self = this;
    for (let rule of rules) {
      if (!rule || !rule.name || !rule.strategy) {
        continue
      }
      let strategyAry = rule.strategy.split(":");
      self.cache.push(function () {
        let strategy = strategyAry.shift();
        let errmsg = rule.errmsg;
        strategyAry.unshift(data[rule.name]);
        strategyAry.push(errmsg);
        return strategys.get(strategy).apply(data, strategyAry);
      });
    }
  }

  check() {
    let res = {
      isOk: true,
      errmsg: ''
    }
    for (let i = 0, fn; fn = this.cache[i++];) {
      let msg = fn(); // 開(kāi)始效驗(yàn) 并取得效驗(yàn)后的返回信息
      if (msg) {
        res = {
          isOk: false,
          errmsg: msg
        };
        break;
      }
    }
    return res
  }
}

/**
 * 工廠模式,便于后期維護(hù)
 */
function getValidator() {
  let validator = new Validator()
  return validator
}

export default getValidator

app.js

import getValidator from './utils/validate';
App({
  getValidator: getValidator
})
const app = getApp()

Page({
  onShow() {
    let validator = app.getValidator()
    let data = {
      username: '323232223'
    }
    validator.addRule(data, [{
        name: 'username',
        strategy: 'isEmpty',
        errmsg: '用戶(hù)名不能為空'
      },
      {
        name: 'username',
        strategy: 'minLength:6',
        errmsg: '用戶(hù)名長(zhǎng)度不能小于6位'
      },
      {
        name: 'username',
        strategy: 'maxLength:8',
        errmsg: '用戶(hù)名長(zhǎng)度不能大于8位'
      }
    ]);
    console.log(validator.check());
  }
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容