欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vue + Element-UI rules实现表单验证(实例)

程序员文章站 2022-06-07 20:07:56
...

1、自定义一个校验规则js

validator.js

//验证邮箱
export var reg_email = (rule, value, callback) => {
  const reg = /^[a-zA-Z0-9_-][email protected][a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!value) {
    callback(new Error('请输入邮箱'));
  } else {
    let check = reg.test(value);
    if (!check) {
      callback(new Error('邮箱格式错误'))
    }else{
      return true,
      callback()
    }
  }
}
//验证密码
export var reg_password = (rule, value, callback) => {
  const reg = /^(?![a-zA-Z]+$)(?![0-9]+$)[A-Za-z0-9]{8,18}$/;
  if(!value){
    callback(new Error('请输入密码'));
  }else{
    let check = reg.test(value);
    if (!check) {
      callback(new Error('密码格式错误'))
    }else{
      callback()
    }
  }
}

2、在表单页面引入校验规则,并使用:rulse="rules"绑定

几点需要注意的地方
1)导入需要的验证规则
import {
    reg_email,
    reg_password
  } from '../../js/validator.js'
2)使用:rules="rules"绑定一个rules对象
<el-form label-position="right" :model="loginForm" :rules="rules" ref="loginForm" label-width="0px">...</el-form>
3)对需要验证的表单项添加prop属性
<el-form-item prop="userAccount">
    <el-input v-model="loginForm.userAccount" placeholder="请输入邮箱" prefix-icon="fa fa-user-circle-o" clearable/>
</el-form-item>
4)在rules中配置验证
rules: {
    userAccount: [{
        required: true,
        validator: reg_email,
        trigger: 'blur',
    }]
    ...
}
5)在methods中判断校验结果
this.$refs.loginForm.validate()
    .then(res => {...}) //校验通过执行
    .catch(error => {...}) //校验未通过执行

下面是login.vue完整代码
login.vue

<template>
  <div class="div-login">
    <el-form label-position="right" :model="loginForm" :rules="rules" ref="loginForm" label-width="0px">
      <el-form-item class="form-item-title">
        <span class="span-title">用户登录</span>
      </el-form-item>
      <el-form-item prop="userAccount">
        <el-input v-model="loginForm.userAccount" placeholder="请输入邮箱" prefix-icon="fa fa-user-circle-o" clearable/>
      </el-form-item>
      <el-form-item prop="userPassword">
        <el-input v-model="loginForm.userPassword" placeholder="请输入密码" prefix-icon="fa fa-lock" show-password/>
      </el-form-item>
        <el-button type="primary" @click="submitLogin" :loading="loadingBtn">登 录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    reg_email,
    reg_password
  } from '../../js/validator.js'

  export default {
    name: "Login",
    data() {
      return {
        loadingBtn: false,
        rules: {
          userAccount: [{
            required: true,
            validator: reg_email,
            trigger: 'blur',
          }],
          userPassword: [{
            required: true,
            validator: reg_password,
            trigger: 'blur'
          }]
        },
        loginForm: {
          userAccount: '',
          userPassword: ''
        }
      }
    },
    mounted() {
      var that = this;
    },
    methods: {
      submitLogin() {
          this.loadingBtn = true;
          this.$refs.loginForm.validate() //判断表单验证是否通过,验证通过执行.then(),否则执行.catch()
            .then(res => {
              if (this.loginForm.userAccount == '[email protected]' && this.loginForm.userPassword == 'abcd1998') {
                setTimeout(() => {
                  this.$message({
                    type: 'success',
                    message: '登录成功'
                  });
                  this.loadingBtn = false;
                }, 500);
              } else {
                setTimeout(() => {
                  this.$message({
                    type: 'error',
                    message: '登录失败'
                  });
                  this.loadingBtn = false;
                }, 500);
              }
            })
            .catch(error => {
              setTimeout(() => {
                this.$message({
                  type: 'error',
                  message: '验证失败'
                });
                this.loadingBtn = false;
              }, 500);
            })
        }
      }

    },
    watch: {
      'verifyCode': function() {
        this.isVerifyCode = this.GVerifyCode.validate(this.verifyCode);
        console.log(this.isVerifyCode)
      },
    }
  }
</script>
<style>
</style>