Vue number input

by edwardcahyadi

HTML

<div id="app">
<div>
  <input type="number" v-model.number="price" @input="handleInput"/>
</div>
</div>

CSS

body {
  padding: 2rem;
}

Vue

new Vue({
  el: "#app",
  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
    }
  }
})