vue 限制 input 只能输入正负数并最多2位小数

mac2024-05-20  30

先给饿了么input 绑上方法

<el-input v-model="educationReserve.monthMoney" placeholder="" size="small" @input.native="educationReserve.monthMoney= educationReserve.monthMoney.replace (educationReserve.monthMoney,RestrictedMoney (educationReserve.monthMoney))" @change="materielExtraCostChange(educationReserve.monthMoney)"/>

通过监听输入走一个公共方法过滤:

plusOrMinus(values) { let newValue; if (!(/[^0-9.-]/g.test(values))) { newValue = values.replace(/[^\-\d.]/g, '').replace(/\-{2,}/g, '-').replace(/\-{2,}/g, '-').replace(/^\./g, '') .replace(/\.{2,}/g, '.') .replace('.', '$#$') .replace(/\./g, '') .replace('$#$', '.'); if (newValue.toString().indexOf('.') > 0 && Number(newValue.toString().split('.')[1].length) > 2) { newValue = parseInt(parseFloat(newValue) * 100) / 100; } if ((newValue.toString().split('-').length - 1) > 1) { newValue = parseFloat(newValue) || ''; } if ((newValue.toString().split('-').length) > 1 && newValue.toString().split('-')[0].length > 0) { newValue = parseFloat(newValue) || ''; } if (newValue.toString().length > 1 && (newValue.toString().charAt(0) === '0' || (newValue.toString().length > 2 && newValue.toString().charAt(0) === '-' && newValue.toString().charAt(1) === '0' && newValue.toString().charAt(2) !== '.')) && newValue.toString().indexOf('.') < 1) { newValue = parseFloat(newValue) || ''; } // 判断整数位最多为9位 if (newValue.toString().indexOf('.') > 0 && Number(newValue.toString().split('.')[0].length) > 9) { newValue = `${newValue.toString().substring(0, 9)}.${newValue.toString().split('.')[1]}`; } else if (newValue.toString().indexOf('.') < 0 && Number(newValue.toString().split('.')[0].length) > 9) { newValue = newValue.toString().substring(0, 9); } } else { newValue = values.replace(/[^0-9.-]/g, ''); } return newValue; },

下面 2 个是input方法:

// 额外费用校验输入正负数, 保留2位小数 调用公共方法 RestrictedMoney(values) { return this.plusOrMinus(values.toString()); }, // 结合change事件对失去焦点进行判断,防止输入一些无效值 materielExtraCostChange(item) { // 防止删除为空 if (!item) { item = '0.00'; } // 一些错误金额输入的判断 if (item.toString().indexOf('.') > 0 && Number(item.toString().split('.')[1].length) < 1) { item = item.toString().split('.')[0]; } // 一些错误金额输入的判断 if (!item || item === '-' || item === '-0') { item = '0.00'; return; } item = parseFloat(item).toFixed(2); this.educationReserve.monthMoney = item ; },

现在 input 只能输入 1.11 、 -1.11、1

最新回复(0)