input輸入框限制只能輸入數字和一個小數點
阿新 • • 發佈:2021-01-09
專案要求輸入框只能輸入數字和一個小數點,長度最多16位,小數點保留兩位小數
<input type="number" @keyup="proving(index)" onKeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))" v-model="item.value" placeholder="請輸入" />
// type = number 型別時不能限制輸入框輸入 - + e 字元,加下面一行限制
// onKeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
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) } }