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

如何限制日/月表单输入最大值?(日≤31,月≤12)

解决方案:日/月输入框的实时校验与提交验证

我来帮你搞定这个日期输入的有效性限制问题!结合你现有的掩码函数,我们可以从实时输入校验和表单提交验证两个层面入手,确保用户无法输入无效的日/月值。

1. 增强掩码函数的实时校验

我们可以在掩码的配置中添加onKeyPress和onChange事件,在用户输入过程中就拦截无效值,同时处理粘贴或修改后的异常情况:

function maskFormatterForData(val) {
  $(val).mask("ZZ / ZZ", {
    translation: {
      'Z': {
        pattern: /[0-9]/,
        optional: true
      }
    },
    // 实时按键校验,拦截无效输入
    onKeyPress: function(inputVal, e, field, options) {
      const cleanVal = field.val().replace(/\s/g, '');
      const currentLength = cleanVal.length;
      const pressedChar = String.fromCharCode(e.which);

      // 校验日期部分(第1、2位)
      if (currentLength === 1) {
        // 日期第一位不能大于3
        if (pressedChar > '3') e.preventDefault();
      } else if (currentLength === 2) {
        const firstDayChar = cleanVal[0];
        // 若日期第一位是3,第二位不能大于1
        if (firstDayChar === '3' && pressedChar > '1') e.preventDefault();
      }

      // 校验月份部分(第3、4位)
      if (currentLength === 3) {
        // 月份第一位不能大于1
        if (pressedChar > '1') e.preventDefault();
      } else if (currentLength === 4) {
        const firstMonthChar = cleanVal[2];
        // 若月份第一位是1,第二位不能大于2
        if (firstMonthChar === '1' && pressedChar > '2') e.preventDefault();
      }
    },
    // 输入完成后修正异常值(比如粘贴了无效内容)
    onChange: function(val) {
      const cleanVal = val.replace(/\s/g, '');
      const [day, month] = cleanVal.split('/');
      let correctedVal = '';

      // 修正日期:超过31则设为31
      const validDay = day ? (parseInt(day) > 31 ? '31' : day) : '';
      // 修正月份:超过12则设为12
      const validMonth = month ? (parseInt(month) > 12 ? '12' : month) : '';

      if (validDay && validMonth) {
        correctedVal = `${validDay.padStart(2, '0')} / ${validMonth.padStart(2, '0')}`;
      } else if (validDay) {
        correctedVal = `${validDay.padStart(2, '0')} / `;
      } else if (validMonth) {
        correctedVal = ` / ${validMonth.padStart(2, '0')}`;
      }

      if (correctedVal !== val) {
        $(this).val(correctedVal);
      }
    }
  });
}

2. 表单提交时的最终验证

为了防止用户通过浏览器控制台或其他方式绕过实时校验,我们需要在表单提交时做一次最终验证,甚至可以加入更精确的月份天数校验(比如2月最多29天、4/6/9/11月最多30天):

// 假设你的表单id为"dateForm",根据实际情况修改
$('#dateForm').submit(function(e) {
  const inputVal = $('#dtDateFrom').val().replace(/\s/g, '');
  const [day, month] = inputVal.split('/');

  // 验证月份有效性
  if (!month || parseInt(month) < 1 || parseInt(month) > 12) {
    alert('请输入有效的月份(1-12)');
    e.preventDefault();
    $('#dtDateFrom').focus();
    return false;
  }

  // 验证日期有效性
  if (!day || parseInt(day) < 1 || parseInt(day) > 31) {
    alert('请输入有效的日期(1-31)');
    e.preventDefault();
    $('#dtDateFrom').focus();
    return false;
  }

  // 可选:更精确的月份天数校验(考虑闰年)
  const currentYear = new Date().getFullYear();
  let maxDays = [31,28,31,30,31,30,31,31,30,31,30,31][parseInt(month)-1];
  // 闰年2月处理
  if (parseInt(month) === 2 && ((currentYear % 4 === 0 && currentYear % 100 !== 0) || currentYear % 400 === 0)) {
    maxDays = 29;
  }
  if (parseInt(day) > maxDays) {
    alert(`该月份最多只有${maxDays}天,请输入有效的日期`);
    e.preventDefault();
    $('#dtDateFrom').focus();
    return false;
  }

  return true;
});

3. 使用方式

确保你的页面已经引入了jQuery和jQuery Mask插件,然后在页面加载完成后初始化输入框:

$(document).ready(function() {
  maskFormatterForData('#dtDateFrom');
});

这样就能全方位限制用户输入无效的日/月值啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:01:48