如何用JavaScript实现银行卡有效期3个月内过期的校验功能
银行卡有效期校验实现方案
核心规则梳理
首先明确业务前提:
- 后端返回值为3/4位数字,最后两位为年份后两位,剩余前缀为月份,例:
424= 4月2024年,1121= 11月2021年 - 银行卡有效期默认到当月最后一天的23:59:59
- 若到期时间距离当前日期不足3个月,标记为无效,展示错误样式
原有代码问题说明
你当前的实现存在几个明显缺陷:
d.getDate()获取的是当前日期的「日」,无法拿到正确的月份、年份基准值- 直接用字符串拼接比较大小,跨年份场景会判断错误(比如当前12月加3个月到次年3月的场景无法兼容)
- 没有做月份合法性校验,后端返回异常值时会导致逻辑异常
可行实现方案
function validateCardExpiry(expValue) { const now = new Date(); // 1. 拆分有效期的月和年 const expStr = expValue.toString(); const expYearSuffix = expStr.slice(-2); const expMonth = parseInt(expStr.slice(0, -2), 10); // 转成4位完整年份,默认按20xx年处理,可根据业务范围调整 const expYear = 2000 + parseInt(expYearSuffix, 10); // 2. 基础合法性校验:月份必须在1-12区间内 if (expMonth < 1 || expMonth > 12) { const invalidHtml = `<span class="text-danger">${expStr.slice(0, -2).padStart(2, '0')}/${expYearSuffix}</span>`; return this.sanitizer.bypassSecurityTrustHtml(invalidHtml); } // 3. 计算到期时间:到期当月最后一天的最后一刻 const expiryDate = new Date(expYear, expMonth, 0, 23, 59, 59); // 4. 计算阈值时间:当前时间往后加3个月 const thresholdDate = new Date(now); thresholdDate.setMonth(now.getMonth() + 3); // 5. 对比返回对应样式 const formatMonth = expMonth.toString().padStart(2, '0'); if (expiryDate < thresholdDate) { // 不足3个月到期,标红展示 return this.sanitizer.bypassSecurityTrustHtml(`<span class="text-danger">${formatMonth}/${expYearSuffix}</span>`); } // 有效期正常 return this.sanitizer.bypassSecurityTrustHtml(`${formatMonth}/${expYearSuffix}`); }
示例匹配验证
以你给出的测试用例为例,假设基准当前时间为2021年10月,加3个月后的阈值为2022年1月:
- 1221 → 2021年12月31日 < 2022年1月 → 无效,符合输出要求
- 1121 → 2021年11月30日 < 2022年1月 → 无效,符合输出要求
- 122 → 2022年1月31日,可根据业务需求调整判断条件(加等于即可匹配你给出的无效输出)
- 221、222到期时间均晚于阈值 → 有效,符合输出要求
内容的提问来源于stack exchange,提问作者vinuta
相关产品推荐
相关产品推荐

