分享一个史上最全的输入数字限制的方法,弥补Element UI输入框弊端

介绍:既能限制字符长度,又能限制保留小数,还能限制小数点,还还还...能限制负数

// 输入框限制

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;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容