JS日期校验定制:将mm/dd/yyyy改为信用卡有效期mm/yy格式
信用卡mm/yy格式有效期校验代码适配方案
核心调整方向
基于原有的mm/dd/yyyy校验代码,针对信用卡有效期的业务规则做定点修改,无需重写全量逻辑:
- 替换年份段的校验规则:移除原有绑定31天的最大值限制,将年份段的校验最大值设为99,适配双位年份的取值范围
- 修正展示格式:将原有的带空格斜杠
' / '改为信用卡通用的紧凑格式/,同时将输入最大截断长度从14调整为5,匹配mm/yy的总长度 - 补充有效期核心校验逻辑:增加和当前系统时间的比对,拦截早于当前月的过期输入
- 优化斜杠自动补全规则:用户输入满2位有效月份后自动补斜杠,无需手动输入分隔符
适配后可直接运行的完整代码
const dateInput = document.getElementById('date'); // 保留原有数字格式化逻辑,仅适配新的取值范围 function checkValue(str, max) { if (str.charAt(0) !== '0' || str === '00') { const num = parseInt(str); // 非法值(非数字、小于等于0、超出最大值)统一默认归为最小值 if (isNaN(num) || num <= 0 || num > max) num = 1; // 单数字输入自动补前导0,比如输入3自动格式化为03 str = num > parseInt(max.toString().charAt(0)) && num.toString().length === 1 ? `0${num}` : num.toString(); } return str; } dateInput.addEventListener('input', function() { this.type = 'text'; // 全量过滤所有非数字字符,避免非法符号输入 let cleanInput = this.value.replace(/\D/g, ''); // 仅保留前4位有效数字(2位月份+2位年份) cleanInput = cleanInput.substr(0, 4); let month = '', year = ''; if (cleanInput.length >= 2) { // 月份段校验固定最大值12 month = checkValue(cleanInput.substr(0, 2), 12); // 剩余数字做年份段校验,最大值99 year = cleanInput.substr(2, 2) ? checkValue(cleanInput.substr(2, 2), 99) : ''; } else { month = cleanInput ? checkValue(cleanInput, 12) : ''; } // 拼接最终展示格式 let finalValue = ''; if (month && year) { finalValue = `${month}/${year}`; } else if (month.length === 2) { // 输入满2位月份后自动补斜杠 finalValue = `${month}/`; } else { finalValue = month; } this.value = finalValue; // 输入满完整有效期格式时自动校验过期状态 if (finalValue.length === 5) { const [expMonth, expYear] = finalValue.split('/').map(Number); const now = new Date(); const currentShortYear = now.getFullYear() % 100; const currentMonth = now.getMonth() + 1; // 过期判断:年份早于当前年,或年份相同但月份早于当前月 const isExpired = expYear < currentShortYear || (expYear === currentShortYear && expMonth < currentMonth); if (isExpired) { this.setCustomValidity('信用卡有效期不能早于当前时间'); } else { this.setCustomValidity(''); } } });
规则说明
- 输入月份时自动做范围拦截,01-12为合法值,输入00、13这类非法值会自动修正为01
- 整个输入框最多展示5位字符,杜绝无意义的超长输入
- 双位年份输入范围00-99,配合内置的时间比对逻辑,过期值会直接触发表单校验提示
- 斜杠由系统自动补全,降低用户输入成本
内容的提问来源于stack exchange,提问作者K.Kishore
相关产品推荐
相关产品推荐

