介绍:既能限制字符长度,又能限制保留小数,还能限制小数点,还还还...能限制负数
// 输入框限制
export function sanitizeInputRow(row, field, val, allowNegative = false) {
let newVal = val;
if (allowNegative) {
// 允许负号:保留数字、小数点和负号
newVal = newVal.replace(/[^\d.\-]/g, '');
const isNegative = newVal.startsWith('-');
newVal = newVal.replace(/-/g, ''); // 移除所有负号
if (isNegative) {
newVal = '-' + newVal; // 如果原本以负号开头,则重新添加
}
} else {
// 不允许负号:只保留数字和小数点
newVal = newVal.replace(/[^\d.]/g, '');
}
// 限制只一个小数点
const parts = newVal.split('.');
if (parts.length > 2) {
newVal = parts[0] + '.' + parts.slice(1).join('');
}
// 去除前导 0(仅整数部分)
if (!newVal.includes('.')) {
newVal = newVal.replace(/^0+(\d)/, '$1');
}
// 限制小数点后最多 3 位
const match = newVal.match(/^(-?\d+)(\.\d{0,3})?/);
if (match) {
newVal = match[1] + (match[2] || '');
}
if (newVal.startsWith('-.')) {
newVal = newVal.replace('-.' , '-0.');
} else if (newVal.startsWith('.')) {
newVal = '0' + newVal;
}
// 回写值
row[field] = newVal;
}