策略模式实现vue2+elementui表单验证

2 篇文章 0 订阅

场景:当我们在使用elementui表单自定义验证时,需要去写很多验证规则,也会产生很多if-else,这时候我们就可以使用策略模式来将一系列的验证封装起来再调用,这样代码就会清晰很多,就不会显得很乱,也避免了一大堆if-else,并且里面的方法也可以复用。

vue部分
<template>
  <div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="密码" prop="pwd">
        <el-input type="password" v-model="ruleForm.pwd" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="surePwd">
        <el-input type="password" v-model="ruleForm.surePwd" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="ruleForm.age"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import Validator from "@/strategies/strategy1.js";
const validate = new Validator();
export default {
  data() {
    return {
      ruleForm: {
        pwd: "",
        surePwd: "",
        age: "",
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  computed: {
    rules() {
      return {
        pwd: [{ validator: validate.checkFormPwd(), trigger: "blur" }],
        surePwd: [{ validator: validate.checkFormSurePwd(this.ruleForm), trigger: "blur" }],
        age: [{ validator: validate.checkFormAge(), trigger: "blur" }]
      }
    }
  }
};
</script>
strategy.js部分
class Strategy {
    getParams(data, flag = false) {
        if (!flag) {
            return { value: data[0], errMsg: data[1] }
        }
        return { value: data[0], errMsg: data[1], oldValue: data[2] }
    }
    checkIsNull(...args) {
        const { value, errMsg } = this.getParams(args)
        if (value === "" || value === null) return errMsg
    }
    checkIsAdult(...args) {
        const { value, errMsg } = this.getParams(args)
        if (value < 18) return errMsg
    }
    checkAgeIsNumber(...args) {
        const { value, errMsg } = this.getParams(args)
        if (isNaN(value)) return errMsg
    }
    checkPwd(...args) {
        const { value, errMsg } = this.getParams(args)
        if (!/[A-Za-z]/.test(value)) return errMsg
    }
    checkSurePwd(...args) {
        const { value, errMsg, oldValue } = this.getParams(args, true)
        if (value !== oldValue) return errMsg
    }
}

const strategy = new Strategy();

export default class Validator {
    constructor() {
        this.cache = []
    }

    reset() {
        this.cache = []
    }

    add(checkName, errMsg, ...args) {
        this.cache.push(function () {
            return strategy[checkName](args[0], errMsg, args[1])
        })
    }

    startCheck(params) {
        for (let i = 0; i < this.cache.length; i++) {
            let fn = this.cache[i]
            let errMsg = fn(params);
            if (errMsg) return errMsg
        }
    }

    checkFormAge() {
        return (rule, value, callback) => {
            this.reset();
            this.add("checkIsNull", "年龄不能为空", value);
            this.add("checkAgeIsNumber", "年龄必须为数字", value);
            this.add("checkIsAdult", "年龄必须大于18", value);
            let message = this.startCheck();
            if (message) return callback(new Error(message));
            callback();
        }
    }

    checkFormPwd() {
        return (rule, value, callback) => {
            this.reset();
            this.add("checkIsNull", "密码不能为空", value);
            this.add("checkPwd", "密码格式不正确", value);
            let message = this.startCheck();
            if (message) return callback(new Error(message));
            callback();
        }
    }

    checkFormSurePwd(ruleForm) {
        return (rule, value, callback) => {
            this.reset();
            this.add("checkIsNull", "确认密码不能为空", value,);
            this.add("checkPwd", "密码格式不正确", value,);
            this.add("checkSurePwd", "两次密码不一致", value, ruleForm.pwd);
            let message = this.startCheck();
            if (message) return callback(new Error(message));
            callback();
        }
    }
}

当然这里只写了很简单的两个验证,哈哈哈,主要是记录一下这个思路。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值