«

怎么用vue代码实现表单数据验证

时间:2024-4-10 10:24     作者:韩俊     分类: Javascript


这篇文章主要讲解了“怎么用vue代码实现表单数据验证”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用vue代码实现表单数据验证”吧!

  • 为el-form表单添加:rules

  • 在data中定义规则

  • 将定义的规则绑定在el-form-item

代码如下:

<!--登录表单区域-->
  <el-form :model="loginform" label-width="0px" class="login_form" :rules="loginformrules">
  <!--用户名-->
   <el-form-item prop="username">
    <el-input v-model="loginform.username" prefix-icon="el-icon-user"></el-input>
  </el-form-item>
  <!--密码-->
  <el-form-item prop="password">
    <el-input v-model="loginform.password" prefix-icon="el-icon-lock" type="password"></el-input>
  </el-form-item>
  <!--按钮区域-->
  <el-form-item class="btns">
    <el-button type="primary">登录</el-button>
    <el-button type="info">重置</el-button>
  </el-form-item>
  </el-form>
<script>
 export default{
 data(){
  return {
  //登录表单数据绑定对象
  loginform:{
   username:'',
   password:''
  },
  //表单验证规则
  loginformrules:{
   //验证用户名是否合法
   username:[
   { required: true, message: '请输入用户名', trigger: 'blur' },
   { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
   ],
   //验证密码是否合法
   password:[
   { required: true, message: '请输入密码', trigger: 'blur' },
   { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
   ]
  }
  }
 }
 }
</script>

ps:下面看下vue 自定义指令input表单的数据验证的代码

<template>
  <div class="check" >
    <h3>{{msg}}</h3>
    <div class="input">
      <input type="text" v-input v-focus><span>{{msg1}}</span>
    </div>
    <div class="input">
      <input type="text" v-input v-required><span>{{msg2}}</span>
    </div>
    <div class="input">
      <!-- required:true/false 表示这个是必填项 -->
      <input type="text" v-input v-checked="{required:true,}"><span>{{msg3}}</span>
    </div>
    <div class="input">
      <!-- <input type="text" v-input v-validate="'required|email|phone|min(5)|max(15)|minlength(6)|maxlength(12)|regex(/^[0-9]*$/)'">
      required 验证是否是必填项
      email 验证是否是邮箱
      phone 验证是否是电话号码
      min(5) 验证最小值
      max(3) 验证最大值
      minlength(6) 验证最小长度
      maxlength(12) 验证最大长度
      regex(/^[0-9]*$/) 进行正则验证
      -->
      <input type="text" v-input
          v-validate="'required|min(5)|max(15)|minlength(6)|maxlength(12)|regex(/^[0-9]*$/)'" placeholder="多选验证">
    </div>
    <div class="input">
      <!--
      验证必须是数字:/^[0-9]*$/
      验证由26个英文字母组成的字符串:/^[a-za-z]+$/
      验证手机号: /^[1][3,4,5,7,8][0-9]{9}$/;
      验证邮箱:/^(w-*.*)+@(w-?)+(.w{2,})+$/;
      -->
      <input type="text" v-input v-validate="'required|phone'" placeholder="验证手机号码">
    </div>
    <div class="input">
      <input type="text" v-input v-validate="'required|email'" placeholder="验证邮箱">
    </div>
  </div>
</template>

<script>
  export default {
    name: 'check',
    data() {
      return {
        msg: '指令',
        tipsbordercolor: 'red',
        msg1: '最简单的指令',
        msg2: '验证不能为空的指令',
        msg3: '进行正则验证',
        tipsmsg: '',
      }
    },

    directives: {
      // 修饰input框的指令
      input: {
        // 当被绑定的元素插入到dom上的时候
        inserted: function (el) {
          el.style.width = "300px";
          el.style.height = "35px";
          el.style.lineheight = "35px";
          el.style.background = "#ddd";
          el.style.fontsize = "16px";
          el.style.border = "1px solid #eee";
          el.style.textindent = "5px";
          el.style.textindent = "8px";
          el.style.borderradius = "5px";
        }
      },
      // input框默认选中的指令
      focus: {
        inserted: function (el) {
          el.focus();
        }
      },
      // 不能为空的指令
      required: {
        inserted: function (el) {
          el.addeventlistener('blur', function () {
            if (el.value == '' || el.value == null) {
              el.style.border = "1px solid red";
              console.log('我不能为空');
            }

          })
        }
      },
      // 验证指令
      checked: {
        inserted: function (el) {
          return el
        }
      },
      // 验证
      validate: {
        inserted: function (el, validatestr) {
          // 将验证规则拆分为验证数组
          let validaterulearr = validatestr.value.split("|");
          // 监听失去焦点的时候
          el.addeventlistener('blur', function () {
            //失去焦点进行验证
            checkedfun();
          });

          // 循环进行验证
          function checkedfun() {
            for (var i = 0; i < validaterulearr.length; ++i) {
              let requiredregex = /^required$/; // 判断设置了required
              let emailregex = /^email$/; // 判断设置了email
              let phoneregex = /^phone$/; // 判断设置了 phone
              let minregex = /min(/; //判断设置了min 最小值
              let maxregex = /max(/; //判断设置了max 最大值
              let minlengthregex = /minlength(/; //判断设置了 minlength 最大长度
              let maxlengthregex = /maxlength(/; //判断设置了 maxlength 最大长度
              let regexregex = /regex(/;
              // 判断设置了required
              if (requiredregex.test(validaterulearr[i])) {
                if (!required()) {
                  break;
                } else {
                  removetips();
                }

              }

              // 判断设置了email
              if (emailregex.test(validaterulearr[i])) {
                if (!email()) {
                  break;
                } else {
                  removetips();
                }

              }

              // 判断设置了 phone
              if (phoneregex.test(validaterulearr[i])) {
                if (!phone()) {
                  break;
                } else {
                  removetips();
                }

              }

              // 判断是否设置了最小值
              if (minregex.test(validaterulearr[i])) {
                if (!eval(validaterulearr[i])) {
                  break;
                } else {
                  removetips();
                }

              }

              // 判断是否设置了最大值
              if (maxregex.test(validaterulearr[i])) {
                if (!eval(validaterulearr[i])) {
                  break;
                } else {
                  removetips();
                }

              }

              // 判断设置了最小长度
              if (minlengthregex.test(validaterulearr[i])) {
                if (!eval(validaterulearr[i])) {
                  break;
                } else {
                  removetips();
                }

              }

              // 判断设置了最大长度
              if (maxlengthregex.test(validaterulearr[i])) {
                if (!eval(validaterulearr[i])) {
                  break;
                } else {
                  removetips();
                }

              }

              // 判断测试正则表达式
              if (regexregex.test(validaterulearr[i])) {
                if (!eval(validaterulearr[i])) {
                  break;
                } else {
                  removetips();
                }

              }

            }

          }

          // 验证是否是必填项
          function required() {
            if (el.value == '' || el.value == null) {
              // console.log("不能为空");
              tipmsg("不能为空");
              return false;
            }

            return true;
          }

          // 验证是否是邮箱
          function email() {
            let emailrule = /^(w-*.*)+@(w-?)+(.w{2,})+$/;
            if (!emailrule.test(el.value)) {
              tipmsg("请输入正确的邮箱地址");
              return false;
            }

            return true;
          }

          // 验证是否是手机号码
          function phone() {
            let phonerule = /^[1][3,4,5,7,8][0-9]{9}$/;
            if (!phonerule.test(el.value)) {
              tipmsg("请输入正确的手机号码");
              return false;
            }

            return true;
          }

          // 最小值验证
          function min(num) {
            if (el.value < num) {
              tipmsg("最小值不能小于" + num);
              //console.log('最小值不能小于'+num);
              return false;
            }

            return true;
          }

          // 最大值验证
          function max(num) {
            if (el.value > num) {
              tipmsg("最大值不能大于" + num);
              //console.log('最大值不能大于'+num);
              return false;
            }

            return true;
          }

          // 最小长度验证
          function minlength(length) {
            if (el.value.length < length) {
              //console.log('最小长度不能小于'+length);
              tipmsg("最小长度不能小于" + length);
              return false;
            }

            return true;
          }

          // 最大长度进行验证
          function maxlength(length) {
            if (el.value.length > length) {
              //console.log('最大长度不能大于'+length);
              tipmsg("最大长度不能大于" + length);
              return false;
            }
            return true;
          }

          // 进行正则表达式的验证
          function regex(rules) {
            if (!rules.test(el.value)) {
              tipmsg("请输入正确的格式");
              return false;
            }
            return true;
          }

          // 添加提示信息
          function tipmsg(msg) {
            removetips();
            let tipsdiv = document.createelement('div');
            let curdate = date.parse(new date());
            tipsdiv.innertext = msg;
            tipsdiv.classname = "tipsdiv";
            tipsdiv.id = curdate;
            tipsdiv.style.position = "absolute";
            tipsdiv.style.top = el.offsettop + 45 + 'px';
            tipsdiv.style.left = el.offsetleft + 'px';
            document.body.appendchild(tipsdiv);
            //settimeout(function(){
            // document.getelementbyid(curdate).remove();
            //},2000);
          }

          // 移除提示信息
          function removetips() {
            if (document.getelementsbyclassname('tipsdiv')[0]) {
              document.getelementsbyclassname('tipsdiv')[0].remove();
            }

          }
        },
      }
    }
  }
</script>

<style>

  .input {
    padding-bottom: 20px;
    float: left;
    clear: both;
    margin-left: 500px;
    display: block;

  }

  .check input {
    width: 300px;
    height: 35px;
    outline: none;
    background: #ddd;
  }

  .check span {
    padding-left: 20px;
  }

  .tipsdiv {
    height: 27px;
    line-height: 25px;
    border: 1px solid #333;
    background: #333;
    padding: 0px 5px;
    border-radius: 4px;
    color: #fff;
    font-size: 16px;
  }

  .tipsdiv:before {
    content: '';
    display: block;
    border-width: 0 5px 8px;
    border-style: solid;
    border-color: transparent transparent #000;
    position: absolute;
    top: -9px;
    left: 6px;
  }
</style>

标签: javascript vue

热门推荐