You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript或React实现信用卡到期日期有效性校验

React 信用卡到期日校验完整实现

现有逻辑问题修正

你之前写的月份范围校验正则存在匹配漏洞:

// 原正则:因运算符优先级问题,缺少分组和结尾锚定,会误判13、0012这类非法值
let cardMonth = /^0[1-9]|1[0-2]/.test(e.target.value);

必须修改为带分组和首尾锚定的写法,确保输入值完全匹配01-12的规则:

const monthReg = /^(0[1-9]|1[0-2])$/;

过期判断核心逻辑

纯正则无法实现和实时日期绑定的过期校验,需要结合当前系统时间做分层判断,规则完全匹配需求:当前为2022年6月时,仅07/22及之后的日期有效。
判断逻辑分层如下:

  • 输入年份小于当前年份后两位:直接判定过期
  • 输入年份大于当前年份后两位:直接判定有效
  • 输入年份等于当前年份后两位:输入月份必须大于当前自然月才判定为有效
  • 注意JS的getMonth()返回值为0-11(对应1-12月),取值后需要加1才是实际月份数字

因为月份、年份是两个独立输入框,任意一个框失焦时都要同时取两个字段的值做联合校验,不能只校验当前输入框的内容,避免漏判。

完整可复用代码

// 输入时的数字限制逻辑,月、年输入框可复用
const handleInput = (e) => {
  const { name, value } = e.target;
  setInput({ 
    ...input, 
    [name]: value.replace(/\D/g, "").slice(0, 2) 
  });
};

// 失焦校验逻辑,绑定到月、年两个输入框的onBlur事件
const handleBlur = (e) => {
  const { name, value } = e.target;
  const formatVal = value.replace(/\D/g, "").slice(0, 2);
  const newInput = { ...input, [name]: formatVal };
  setInput(newInput);

  const newErrors = { ...errors };
  // 校验月份格式合法性
  const isMonthValid = /^(0[1-9]|1[0-2])$/.test(newInput.cardMonth);
  newErrors.cardmonth = !isMonthValid;
  // 校验年份格式合法性(必须为2位数字)
  const isYearValid = /^\d{2}$/.test(newInput.cardYear);
  newErrors.cardyear = !isYearValid;

  // 格式全部合法时再做过期判断
  newErrors.expired = false;
  if (isMonthValid && isYearValid) {
    const now = new Date();
    const currentYearShort = now.getFullYear() % 100;
    const currentMonth = now.getMonth() + 1; // 转成1-12的自然月
    const inputMonth = parseInt(newInput.cardMonth, 10);
    const inputYear = parseInt(newInput.cardYear, 10);

    if (inputYear < currentYearShort) {
      newErrors.expired = true;
    } else if (inputYear === currentYearShort) {
      // 若业务调整为到期当月有效,把<=改成<即可
      newErrors.expired = inputMonth <= currentMonth;
    }
  }

  setErrors(newErrors);
};

错误提示对应

可根据errors里的字段返回对应提示:

  • cardmonth: true:月份必须为01-12之间的数字
  • cardyear: true:请输入2位数字的年份
  • expired: true:到期日期已过期,请输入有效日期

内容的提问来源于stack exchange,提问作者Sudhir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 12:21:19