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

新手上路,请多包涵

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

原文由 Saviah Kao 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 608
2 个回答

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

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

原文由 Saviah Kao 发布,翻译遵循 CC BY-SA 4.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/

原文由 Edward Cahyadi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题