Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Only allow users to key in value like currency in a text box by using Vue.js

like image 445
Saviah Kao Avatar asked Oct 07 '18 06:10

Saviah Kao


1 Answers

Working example: https://jsfiddle.net/0s14cbqx/

In template:

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

In 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();
     }
   }
}

In this way, users only can key in numbers and one dot and can't key in anything after 2 decimal places.

like image 156
Saviah Kao Avatar answered Nov 03 '22 02:11

Saviah Kao