enter currency value in text box

Only allow numbers and one dot with 2 decimal places restriction in keypress vuejs

by kaochihhui

HTML

<div id="app">
  <input placeholder="Name a price" v-model="price" @keypress="onlyForCurrency">
</div>

Vue

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