在 keypress vuejs 中只允许数字和一个点有 2 个小数位限制
Only allow numbers and one dot with 2 decimal places restriction in keypress vuejs
只允许用户使用 Vue.js
在文本框中输入 currency 等值
工作示例: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();
}
}
}
这样用户只能输入数字和一个点,不能输入小数点后2位。
对于带有类型编号的输入,这是我们确定的:
<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/
使用 autoNumeric
Javascript 库效果很好。
有一个 Vue.js 组件包装它:vue-autoNumeric
。
此外,它适用于 Vuetify
's v-text-field
, see https://codesandbox.io/s/yw07v978mj。
只允许用户使用 Vue.js
在文本框中输入 currency 等值工作示例: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();
}
}
}
这样用户只能输入数字和一个点,不能输入小数点后2位。
对于带有类型编号的输入,这是我们确定的:
<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/
使用 autoNumeric
Javascript 库效果很好。
有一个 Vue.js 组件包装它:vue-autoNumeric
。
此外,它适用于 Vuetify
's v-text-field
, see https://codesandbox.io/s/yw07v978mj。