前端vue中使用Element UI表单校验 及密码复杂度校验组件

在使用表单提交数据时,表单校验可对输入数据进行验证,保证输入数据的格式正确。

表单校验

<template>
  <div class="container">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="密码" prop="pass">
        <el-input
          type="password"
          v-model="ruleForm.pass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <password-line :passwordVal="ruleForm.pass"></password-line>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
          type="password"
          v-model="ruleForm.checkPass"
          autocomplete="off"
        ></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 PasswordLine from "./PasswordLine"; // 引入密码复杂度校验组件
export default {
  components: {
    PasswordLine,
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        pass: "",
        checkPass: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: ["blur", "change"] }],
        checkPass: [{ validator: validatePass2, trigger: ["blur", "change"] }],
      },
    };
  },
  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();
    },
  },
};
</script>
<style scoped>
.container {
  padding-right: 100px !important;
  padding: 30px;
  width: 400px;
  height: 200px;
  border: 2px dashed skyblue;
}
</style>

密码复杂度校验组件

PasswordLine.vue

<template>
  <div class="line-container" v-show="showProgress">
    <div
      class="line"
      :style="{ width: `${progressPercent}%`, background: bgColor }"
    ></div>
    <div class="tipWord" :style="{ color: bgColor }">
      {{ tipWord }}
    </div>
  </div>
</template>

<script>
export default {
  name: "PasswordLine",
  props: {
    passwordVal: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      bgColor: "",
      tipWord: "",
    };
  },
  watch: {
    progressPercent(v) {
      if (v === 95) {
        this.bgColor = "#64BC38";
        this.tipWord = "Complex";
      } else if (v === 50) {
        this.bgColor = "#FAAD14";
        this.tipWord = "Medium";
      } else {
        this.bgColor = "#F56C6C";
        this.tipWord = "Simple";
      }
    },
  },
  computed: {
    showProgress() {
      return this.passwordVal.length >= 8;
    },
    progressPercent() {
      if (!this.passwordVal) return 0;
      // n:数字  l:小写字母  u:大写字母  s:特殊字符
      const result = this.passwordVal
        .split("")
        .map((val) => val.charCodeAt())
        .reduce(
          (pre, val, index) => {
            if (val < 48) pre.special += 1;
            else if (val < 58) pre.num += 1;
            else if (val < 65) pre.special += 1;
            else if (val < 91) pre.upper += 1;
            else if (val < 97) pre.special += 1;
            else if (val < 123) pre.lower += 1;
            else pre.special += 1;
            return pre;
          },
          { num: 0, lower: 0, upper: 0, special: 0 }
        );

      const arr = Object.values(result);

      const len = this.passwordVal.length;
      const zCount = this.zeroCount(arr)["0"];

      if (len >= 8) {
        if (!zCount) {
          return 95;
        } else if (zCount === 1 || zCount === 2) {
          return 50;
        } else {
          return 28;
        }
      }
    },
  },
  methods: {
    zeroCount(arr) {
      return arr.reduce((prev, next) => {
        prev[next] = prev[next] + 1 || 1;
        return prev;
      }, {});
    },
  },
};
</script>

<style scoped>
.line-container {
  position: relative;
  top: -10px;
}
.line-container,
.line {
  background: #d9dae0;
  height: 8px;
  border-radius: 4px 5px 5px 4px;
}
.tipWord {
  position: absolute;
  left: 0;
  top: -2px;
  font-size: 12px;
}
</style>

在这里插入图片描述

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Vue使用Element UI进行表单验证可以通过以下步骤来实现: 1. 首先,确保你的项目已经安装了Element UI组件库并正确引入。你可以使用npm或者yarn来安装Element UI,然后在你的Vue组件通过import语句引入所需的组件。 2. 在Vue组件,你可以使用Element UI提供的Form组件来创建表单,并使用Form Item组件来包含表单项。 3. 对于每个表单项,你可以使用Element UI提供的校验规则来定义验证规则。你可以通过设置prop属性来指定验证类型,比如required、email等,并通过设置rules属性来定义具体的验证规则。你还可以通过设置消息属性来定义验证失败时的提示信息。 4. 在表单提交时,你可以调用Element UI提供的validate方法来触发表单验证。如果验证通过,你可以继续处理表单数据;如果验证失败,你可以显示提示信息。 下面是一个示例代码,演示了如何在Vue使用Element UI进行表单验证: ```vue <template> <el-form ref="form" :model="formData" :rules="formRules" label-width="120px"> <el-form-item label="用户名" prop="username"> <el-input v-model="formData.username"></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input v-model="formData.password" type="password"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form-item> </el-form> </template> <script> import { mapActions } from 'vuex'; export default { data() { return { formData: { username: '', password: '', }, formRules: { username: [ { required: true, message: '请输入用户名', trigger: 'blur' }, ], password: [ { required: true, message: '请输入密码', trigger: 'blur' }, ], }, }; }, methods: { ...mapActions(['login']), submitForm() { this.$refs.form.validate((valid) => { if (valid) { // 表单验证通过,继续处理提交逻辑 this.login(this.formData); // 调用Vuex action提交表单数据 } else { // 表单验证失败,显示提示信息 this.$message.error('表单验证失败,请检查输入'); } }); }, }, }; </script> ``` 在上述示例,我们使用Element UIFormFormItem组件来创建了一个包含用户名和密码输入框的表单。通过设置prop属性和rules属性,我们定义了用户名和密码的验证规则。在提交表单时,我们调用了validate方法来触发表单验证,并根据验证结果进行相应的处理。 希望以上信息对你有所帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [使用element-ui +Vue 解决 table 里包含表单验证的问题](https://download.csdn.net/download/weixin_38566180/12849766)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [解决vue+ element ui 表单验证有值但验证失败问题](https://download.csdn.net/download/weixin_38659159/12928895)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [系统基于springboot框架,使用Java+vue编写,为前后端分离的微服务项目](https://download.csdn.net/download/Abelon/88250447)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲起来blingbling

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值