限制最多只能输入一位小数点
首位不能是小数点
小数点后最多只能输入两位
HTML:
<u-input type="digit" placeholder="请填此商品价格" v-model="original_price" @input="handleInput">
<template slot="prefix">
<span style="font-size: 24rpx;color: #353D46;padding-right: 20rpx;">¥</span>
</template>
</u-input>
JS:
handleInput(e) {
let newValue = e || ''; // 获取输入框的当前值,注意uView的u-input可能通过event.detail传递值
let lastChar = newValue.slice(-1); // 获取最后一个字符
let decimalPosition = newValue.indexOf('.'); // 查找小数点的位置
let integerPart = ''; // 整数部分
let decimalPart = ''; // 小数部分
// 如果输入框为空或者只有一个小数点(非法输入),则重置输入框
if (newValue === '.' || (newValue.length === 1 && lastChar === '.')) {
newValue = '';
} else {
// 分离整数部分和小数部分
if (decimalPosition !== -1) {
integerPart = newValue.slice(0, decimalPosition);
decimalPart = newValue.slice(decimalPosition + 1);
// 校验小数部分(最多两位数字)
if (/\D/.test(decimalPart)) {
decimalPart = decimalPart.replace(/\D/g, ''); // 移除非数字字符
}
if (decimalPart.length > 2) {
decimalPart = decimalPart.slice(0, 2); // 截取前两位数字
}
// 重新组装值
newValue = integerPart + '.' + decimalPart;
// 如果整数部分为空且存在小数点,则重置输入框(首位不能是小数点)
if (integerPart === '' && decimalPart !== '') {
newValue = '';
}
} else {
// 没有小数点,只校验整数部分(只允许数字)
if (/\D/.test(newValue)) {
newValue = newValue.replace(/\D/g, ''); // 移除非数字字符
}
}
}
this.$nextTick(() => {
// 更新数据
this.original_price = newValue;
})
}