input输入框价格限定:只能输入正数,小数点后两位,不出现多个小数点,0开头后面不接数字(vue做的)


1.给input绑定keyup函数:

<input
                type="text"
                class="form-control"
                id="inputEmail3"
                v-model="price"
                placeholder="请输入价格"
               @keyup="priceFormat"
              />
 
2.编写priceFormat函数:
priceFormat(){
         //非数字和小数点去掉     
        this.price=this.price.replace(/[^0123456789.]/,"") //之前没注意写错了!!!!
        //防止无输入无限个“.”
        this.price=this.price.replace(/\.+/ ,".")
        //在不是“0.”开头的字符进行修改:“01”=>1
        if(this.price.charAt(0)=="0"&&this.price.charAt(1)!="."&&this.price.length>=2){
          this.price=this.price.replace(/0/ ,"")
        }
        //获取第一个小数点的索引值
        var index=this.price.indexOf('.')
        //获取最后一个小数点的索引值
        var lastIndex=this.price.lastIndexOf('.')
        //判断小数点是不是开头,如果是开头,则去除
        if(index==0){
          this.price=this.price.replace(/\./ ,"")
        }
        //只允许小数点后面有2位字符
        if(index>=1){
          this.price=this.price.substring(0,index+3)          
        }
        //防止小数点后面又出现小数点
        if(index!=lastIndex){
          this.price=this.price.substring(0,index+2) 
        }
           
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM