鍍金池/ 問答/HTML5  HTML/ 如何保證移動端vue只能輸入金額?

如何保證移動端vue只能輸入金額?

如何保證移動端的vue項目,在input中只能輸入金額?包括數字和小數點。 發(fā)現如果調type=‘tel’的話只有數字沒有小數點,調type=‘number’還有其他符號。 監(jiān)聽input動作來去掉符號發(fā)現也不行,不知道是不是自己代碼的問題。

  <input ref="content" type="number" pattern="[0-9]{,6}" @input="handleAmountChange"  v-model.number.trim="money"  />
    handleAmountChange(e) {
      this.money = e.target.value.replace(/[^\d]/g, '')
      // 必須保證第一個為數字而不是.
      this.money = this.money.replace(/^\./g, '0.')
      // 保證只有出現一個.而沒有多個.
      this.money = this.money.replace(/\.{2,}/g, '.')
      // 保證.只出現一次,而不能出現兩次以上
      this.money = this.money
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      // 只能輸入兩個小數
      this.money = this.money.replace(/^()*(\d+)\.(\d\d).*$/, '$1$2.$3')
    },
回答
編輯回答
夕顏
methods:{
    onMoneyBlur(){
        if(!/^[0-9]+(\.?(?=[0-9])[0-9]{0,2})?$/.test(this.money)){
            this.money = 0;
            return;
        }
    }
}
針對.開頭的傳字符串測試為false: xx.test('.1')

數字則為 true 應該是 js 自動轉換了: xx.test(.1)

2017年4月27日 16:42