vue输入框限制字符串长度和输入内容实时验证的实现方式

时间:2024-03-01 14:12:39

一、最简单,通过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>