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(/\D^./,"")
        //防止无输入无限个“.”
        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) 
        }
           
    }

猜你喜欢

转载自www.cnblogs.com/Toulachi/p/11841287.html