Sav*_*Kao 13
工作示例: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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样,用户只能输入数字和一个点,不能输入小数点后两位。
对于带有类型号的输入,这就是我们解决的问题:
<input type="number" v-model.number="price" @input="handleInput">
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
这个想法是检查用户的输入结果。如果它与所需的正则表达式模式不匹配,则我们使用 将数据重置回其先前状态previousPrice
。演示:https : //jsfiddle.net/edwardcahyadi/qj9mw5gk/2/