import dayjs from 'dayjs'; import customParseFormat from 'dayjs/plugin/customParseFormat'; dayjs.extend(customParseFormat); // 注册插件 /** * 过滤输入,只允许数字和最多两位小数 * @param {string} value - 输入框当前值 * @param {boolean} isIntegerOnly - 是否只允许正整数(无小数点),开启时最小值为1,或为传入的值 * @returns {string} 过滤后的合法值 */ export function filterNumberInput(value, isIntegerOnly = false) { // 第一步就过滤所有非数字和非小数点的字符(包括字母) let filtered = value.replace(/[^\d.]/g, ""); // 整数模式处理 if (isIntegerOnly !== false) { // 移除所有小数点 filtered = filtered.replace(/\./g, ""); // 处理前导零 filtered = filtered.replace(/^0+(\d)/, "$1") || filtered; // 空值处理(允许临时删除) if (filtered === "") { return ""; } // 最小值限制 if (filtered === isIntegerOnly || parseInt(filtered, 10) < isIntegerOnly) { return isIntegerOnly; } return filtered; } // 小数模式处理 const parts = filtered.split("."); if (parts.length > 1) { filtered = parts[0] + "." + (parts[1].substring(0, 2) || ""); } // 处理前导零 if (filtered.startsWith("0") && filtered.length > 1 && !filtered.startsWith("0.")) { filtered = filtered.replace(/^0+(\d)/, "$1"); } return filtered; } /** * 时间格式互转:HH:mm → HH:mm:ss;HH:mm:ss → HH:mm * @param {string} timeStr - 输入的时间字符串 * @returns {string} 转换后的时间字符串 */ export const convertTimeFormat = (timeStr) => { if (!timeStr) return '00:00'; // 正则判断格式 const isHms = /^\d{1,2}:\d{2}:\d{2}$/.test(timeStr); // HH:mm:ss const isHm = /^\d{1,2}:\d{2}$/.test(timeStr); // HH:mm if (isHm) { // HH:mm → 解析后格式化为 HH:mm:ss return dayjs(timeStr, 'HH:mm').format('HH:mm:ss'); } if (isHms) { // HH:mm:ss → 解析后格式化为 HH:mm return dayjs(timeStr, 'HH:mm:ss').format('HH:mm'); } // 非法格式兜底 return '00:00'; };