zoukankan      html  css  js  c++  java
  • 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>
    

      

  • 相关阅读:
    attr系列保留方法使用
    利用python的标准库hashlib 的md5()生成唯一的id
    【病因】 神经衰弱的几大病因
    群里看到的一个骗子批八字的例子
    i'll make a man out of you
    It's A Good Day To Die
    两天了。照着SVN的界面画的一个界面。
    起一卦,看看我想要的,依然这么倒霉
    倒霉倒霉真倒霉,这一卦起得和上一卦一样
    只要是倒霉,起卦就能看出来
  • 原文地址:https://www.cnblogs.com/toggle/p/12710554.html
Copyright © 2011-2022 走看看