vue輸入框限制字符串長度和輸入內容實時驗證的實現方式


一、最簡單,通過maxlength和onkeyup

<input maxlength="16" onkeyup="this.value=this.value.replace(/[^\w[!@#.=_~+,./<>?:;'\\\$\%\^\&\*\(\)\-\|\[\]\{\}\{\}]/g,'');" />

代碼中正則是限制除中文外的所有鍵盤字符。

二、通過@input和@change

見代碼:

<input type="text"  v-model="groupName" class="edit-input" ref="groupName"
    @input="changeValue"
    @change="editGroupNameSave(groupInfo.name)" >
changeValue () {
        let leng = this.validateTextLength(this.groupName)
        if (leng >= 15) {
          this.$refs.groupName.maxLength = leng
        } else {
          this.$refs.groupName.maxLength = 30
        }
      },
      validateTextLength (value) {
        // 中文、中文標點、全角字符按1長度,英文、英文符號、數字按0.5長度計算
        let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g
        let mat = value.match(cnReg)
        let length
        if (mat) {
          length = (mat.length + (value.length - mat.length) * 0.5)
          return length
        } else {
          return value.length * 0.5
        }
      }

 

三、通過watch

見代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <input type="text" v-model="items.text" ref="count"/>
        <div  v-html="number"></div>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                number: '100',
                items: {
                    text:'',
                },
            },
            watch:{   //watch()監聽某個值(雙向綁定)的變化,從而達到change事件監聽的效果
                items:{
                    handler:function(){
                        var _this = this;
                        var _sum = 100; //字體限制為100個
                        _this.$refs.count.setAttribute("maxlength",_sum);
                        _this.number= _sum- _this.$refs.count.value.length;
                    },
                    deep:true
                }
            }
        })
    </script>
</body>
</html>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM