keypress vuejs中只允许数字和一个小数点后2位限制

Sav*_*Kao 7 textbox input vue.js vuejs2

仅允许用户使用 Vue.js 在文本框中键入货币等值

Sav*_*Kao 13

工作示例:https : //jsfiddle.net/0s14cbqx/

在模板中:

<input placeholder="Name a price" v-model="price" @keypress="onlyForCurrency">

在js中:

data(){
   return{
     price:null
   }
},
methods: {
   onlyForCurrency ($event) {
     // console.log($event.keyCode); //keyCodes value
     let keyCode = ($event.keyCode ? $event.keyCode : $event.which);

     // only allow number and one dot
     if ((keyCode < 48 || keyCode > 57) && (keyCode !== 46 || this.price.indexOf('.') != -1)) { // 46 is dot
      $event.preventDefault();
     }

     // restrict to 2 decimal places
     if(this.price!=null && this.price.indexOf(".")>-1 && (this.price.split('.')[1].length > 1)){
     $event.preventDefault();
     }
   }
}
Run Code Online (Sandbox Code Playgroud)

这样,用户只能输入数字和一个点,不能输入小数点后两位。

  • 另外 - 输入数字后编辑数字会出现问题。不能回去编辑。我不知道如何改变才能工作......有什么想法吗?这是第二个 if 语句。 (3认同)
  • @Jquestions 如果输入是 type="text" 您可以添加: `$event.target.selectionStart &gt; this.price.indexOf(".")` 到最后一个 if 语句,以仅防止在点后面输入数字。 (2认同)

Edw*_*adi 7

对于带有类型号的输入,这就是我们解决的问题:

<input type="number" v-model.number="price" @input="handleInput">
Run Code Online (Sandbox Code Playgroud)
  data () {
    return {
      price: null,
      previousPrice: null
    }
  },

  methods: {
    handleInput (e) {
      let stringValue = e.target.value.toString()
      let regex = /^\d*(\.\d{1,2})?$/
      if(!stringValue.match(regex) && this.price!== '') {
        this.price = this.previousPrice
      }
      this.previousPrice = this.price
    }
  }

Run Code Online (Sandbox Code Playgroud)

这个想法是检查用户的输入结果。如果它与所需的正则表达式模式不匹配,则我们使用 将数据重置回其先前状态previousPrice。演示:https : //jsfiddle.net/edwardcahyadi/qj9mw5gk/2/