vue 自定義input檢測指令及提交

簡介

寫一個全局注冊指令,用來驗證input
包含:非空驗證,email,phone,密碼,最小值,最大值,最小長度,最大長度,自定義正則
提交時,當前頁面做一個驗證

效果圖

全局注冊指令

assets/js 下邊新建一個directive.js文件,用來放置驗證,及注冊指令

input組件:本文使用的Ant Design of Vue(也可以自己修改成其他input組件,或者自己寫),提示信息的添加和移除需要針對修改

import Vue from 'vue'

var elArr = [];//保存所有input的el
// 全局注冊input驗證
Vue.directive('validate', {
  inserted: function (el, validateStr) {
    // 將驗證規(guī)則拆分為驗證數(shù)組
    let validateRuleArr = validateStr.value.split("|");
    var el = el;
    var elInput = el;
    if (el.className.indexOf('ant-input-password') !== -1) {
      elInput = el.firstChild;
    }
    // 監(jiān)聽失去焦點的時候
    elInput.addEventListener('blur', function () {
      //失去焦點進行驗證
      checkedfun();
    });
    
    //用于提交的時候驗證
    for(let a in elArr){
      if(elArr[a].outerHTML==elInput.outerHTML){
        elArr.splice(a,1);
      }
    }
    elArr.push(elInput);
   
    

    // 循環(huán)進行驗證
    function checkedfun() {
      for (var i = 0; i < validateRuleArr.length; ++i) {
        let requiredRegex = /^required$/; // 判斷設置了required
        let emailRegex = /^email$/; // 判斷設置了email
        let phoneRegex = /^phone$/; // 判斷設置了 phone
        let pwdRegex = /^pwd$/; // 判斷設置了 pwd
        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();
          }

        }
        // 判斷設置了 pwd
        if (pwdRegex.test(validateRuleArr[i])) {
          if (!pwd()) {
            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 (elInput.value == '' || elInput.value == null) {
        // console.log("不能為空");
        tipMsg("該輸入框不能為空哦~");
        return false;
      }

      return true;
    }

    // 驗證是否是郵箱
    function email() {
      let emailRule = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
      if (!emailRule.test(elInput.value)) {
        tipMsg("請輸入正確的郵箱地址");
        return false;
      }

      return true;
    }

    // 驗證是否是手機號碼
    function phone() {
      let phoneRule = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!phoneRule.test(elInput.value)) {
        tipMsg("請輸入正確的手機號碼");
        return false;
      }
      return true;
    }

    // 進行密碼的驗證
    function pwd() {
      let pwdRule = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z._*#$@]{6,12}$/;
      if (!pwdRule.test(elInput.value)) {
        tipMsg("密碼必須由6-12位數(shù)字和字母組成。\n特殊字符包含(. _ * # $ @)");
        return false;
      }
      return true;
    }

    // 最小值驗證
    function min(num) {
      if (elInput.value < num) {
        tipMsg("最小值不能小于" + num);
        // console.log('最小值不能小于'+num);
        return false;
      }

      return true;
    }

    // 最大值驗證
    function max(num) {
      if (elInput.value > num) {
        tipMsg("最大值不能大于" + num);
        //console.log('最大值不能大于'+num);
        return false;
      }

      return true;
    }

    // 最小長度驗證
    function minlength(length) {
      if (elInput.value.length < length) {
        // console.log('最小長度不能小于' + length);
        tipMsg("最小長度不能小于" + length);
        return false;
      }

      return true;
    }

    // 最大長度進行驗證
    function maxlength(length) {
      if (elInput.value.length > length) {
        tipMsg("最大長度不能大于" + length);
        return false;
      }
      return true;
    }

    // 進行正則表達式的驗證
    function regex(rules) {
      if (!rules.test(elInput.value)) {
        tipMsg("請輸入正確的格式");
        return false;
      }
      return true;
    }

    // 添加提示信息
    function tipMsg(msg) {
      removeTips();
      elInput.classList.add('tip_el');
      let tipsDiv = document.createElement('div');
      tipsDiv.innerText = `${msg}`;
      tipsDiv.className = 'tip_msg';
      let parent = el.parentNode;
      if (parent.lastChild == el) {
        parent.appendChild(tipsDiv);
      }
    }

    // 移除提示信息
    function removeTips() {
      elInput.classList.remove('tip_el');
      let parent = elInput.parentNode;
      if (parent.lastChild.className == 'tip_msg') {
        parent.removeChild(parent.lastChild);
      }
      //password
      if (el.className.indexOf('ant-input-password') !== -1) {
        let parent = el.parentNode;
        if (parent.lastChild.className == 'tip_msg') {
          parent.removeChild(parent.lastChild);
        }
      }

    }
  },
});

// 提交驗證
Vue.directive('checkSubmit', {
  inserted: function (el, binding, vNode) {
    el.addEventListener('click', function (event) {
      var evObj = document.createEvent('Event');
      evObj.initEvent('blur', true, true);
      for (let elArrChild of elArr) {
        elArrChild.dispatchEvent(evObj);
      }
      /*
      *有一個參數(shù)
      *eg: v-checkSubmit="submitBtn"
      *參數(shù)為時間名
      */
     let doc = document;
     let submitEvent = binding.value;
     /*
     *有兩個參數(shù)
     *用于一個頁面有兩個確定,或者有其他因素干擾了確定按鈕時使用
     *eg: v-checkSubmit="{submitEvent:submitBtn,cls:'backups_all_input'}"
     *submitEvent:事件名稱
     *cls:需要檢測的class名下的input
     */
      if(binding.value.hasOwnProperty('cls')){
        doc = document.getElementsByClassName(binding.value.cls)[0];
        submitEvent = binding.value.submitEvent;
      }

      let errorInputs = doc.getElementsByClassName('tip_el');//tip_el 檢測不通過的input
      if(errorInputs.length === 0){
        submitEvent();//執(zhí)行提交事件
      }
    })
  }
});


css

css部分我寫在reset.scss全局文件中了

//input 提示樣式
.tip_msg{
    color: $danger_color;
    padding-left: 0;
    display: inline-block;
    // margin-top: -20px;
    animation:  tips .5s linear forwards;
}
.tip_el{
    border :1px solid $danger_color !important;
    border-radius: 4px;
}
.tip_el:focus{
    box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2) !important;
}
@keyframes tips{
    0%{
        opacity: 0;
        // margin-top: -20px;
        padding-left: 0;
    }
    100%{
        opacity: 1;
        // margin-top: 0;
        padding-left: 10px;
    }
}

全局引入

main.js

//全局注冊input驗證
import './assets/js/directive.js'

使用方式

//鼠標離開時驗證
<a-input size="large" placeholder="用戶名" v-model="username" v-validate="'required'"/>
<a-input-password size="large" placeholder="登錄密碼" v-model="password" @blur="blurPwd" v-validate="'required|pwd'"/>

//提交驗證 
//將@click替換成v-checkSubmit,并將submitBtn實踐傳過去
//只有一個驗證
<a-button type="primary" size="large" v-checkSubmit="submitBtn"> 提交 </a-button>
//如果有多個提交按鈕,為了不讓多個按鈕沖突需要多傳一個class參數(shù)
//submitEvent:事件名稱
//cls:需要檢測的class名下的input
<a-button type="primary" size="large"  v-checkSubmit="{submitEvent:okBtn,cls:'popup_check_input'}" >提交 </a-button>


參考資料:# vue 自定義指令input表單的數(shù)據(jù)驗證
在此,抱拳感謝~

轉載請著名出處~
-----*13

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容