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

如何使用Moment.js校验time类型输入框 禁止输入已过去的时间

实现方案

代码示例

HTML 部分

<input type="time" id="timeInput" value />
<!-- 错误提示容器,默认隐藏 -->
<span id="errorTip" style="color: #f5222d; font-size: 14px; display: none;">您不能输入已经过去的时间</span>

JS 逻辑部分

需提前引入Moment.js依赖,校验逻辑如下:

const timeInputDom = document.getElementById('timeInput');
const errorTipDom = document.getElementById('errorTip');

// 监听输入和失焦事件触发校验,可根据业务调整触发时机
timeInputDom.addEventListener('input', timeValidate);
timeInputDom.addEventListener('blur', timeValidate);

function timeValidate() {
  const inputTime = timeInputDom.value;
  // 空值跳过校验,可根据业务需求修改
  if (!inputTime) {
    errorTipDom.style.display = 'none';
    return;
  }

  // 将输入时间和当前时间都统一为当日的时间对象,排除日期对比较的影响
  const inputMoment = moment(inputTime, 'HH:mm');
  // 当前时间取整到分钟,避免秒数差导致的校验误差
  const currentMoment = moment().startOf('minute');

  if (inputMoment.isBefore(currentMoment)) {
    // 校验不通过,显示提示
    errorTipDom.style.display = 'inline';
    // 可选配置:校验不通过时清空输入值
    // timeInputDom.value = '';
  } else {
    // 校验通过,隐藏提示
    errorTipDom.style.display = 'none';
  }
}

注意事项

  • 上述逻辑默认仅校验当日的时间是否早于当前时刻,如果你有跨天选择的需求(比如当前为23:00,允许选择次日01:00),可以自行调整时间对象的日期赋值逻辑。
  • 建议在表单提交时增加二次校验,避免前端规则被绕过导致的异常数据提交。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:24:04