在vue.js中仅允许数字和一个点具有2个小数位的限制

时间:2018-10-07 06:02:48

标签: input vue.js textbox vuejs2

仅允许用户使用Vue.js在文本框中键入 currency 之类的值

3 个答案:

答案 0 :(得分:2)

使用autoNumeric Javascript库效果很好。

有一个将其包装的Vue.js组件:vue-autoNumeric

此外,它与Vuetifyv-text-field配合使用,请参见https://codesandbox.io/s/yw07v978mj

答案 1 :(得分:1)

工作示例: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();
     }
   }
}

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

答案 2 :(得分:0)

对于类型为数字的输入,这是我们要解决的:

<input type="number" v-model.number="price" @input="handleInput">
  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
    }
  }

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

相关问题