input輸入框限制只能輸入數字和一個小數點


項目要求輸入框只能輸入數字和一個小數點,長度最多16位,小數點保留兩位小數

<input
  type="number"
  @keyup="proving(index)"
  v-model="item.value"
  placeholder="請輸入"
/>
 
        
  proving(index){
      // this.list[index].value 是輸入框輸入的值,這里是列表循環出來的輸入框
      // 先把非數字的都替換掉,除了數字和.
      this.list[index].value = this.list[index].value.replace(/[^\d.]/g, '');
      // 必須保證第一個為數字而不是.
      this.list[index].value = this.list[index].value.replace(/^\./g, '');
      // 保證只有出現一個.而沒有多個.
      this.list[index].value = this.list[index].value.replace(/\.{2,}/g, '');
      // 保證.只出現一次,而不能出現兩次以上
      this.list[index].value = this.list[index].value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
      let count = -1
      for (let i in this.list[index].value) {
          if (this.list[index].value[i] === '.') {
              count = i
          }
          if (count !== -1) {
              if (i - count > 2) {
                  this.list[index].value = this.list[index].value.substring(0, this.list[index].value.length - 1)
              }
          }
      }
      // 限制輸入長度最多為16位
      if(this.list[index].value.length > 16){
        this.list[index].value = this.list[index].value.slice(0, 16)
      }
    }

 


免責聲明!

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



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