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

如何用JavaScript实现出生日期输入框自动添加分隔点?

实现HTML输入框出生日期自动格式化(每2字符添加句号)

首先要明确,toLocaleLowerCase() 方法和这个需求无关——它的作用是将字符串转换为小写形式,和日期格式化没有关联。要实现输入出生日期时每输入2个字符自动添加句号,我们可以通过监听输入框的输入事件,用JavaScript处理输入内容来实现。

实现思路

  • 监听输入框的 input 事件,实时处理输入内容
  • 过滤掉输入内容中的非数字字符,只保留有效数字
  • 对数字字符串分段,每2个字符后添加句号
  • 处理光标位置,避免格式化操作导致光标错乱

代码示例

HTML部分

<input type="text" id="birthDateInput" placeholder="输入出生日期(如01011980)" maxlength="10">

JavaScript部分

const birthDateInput = document.getElementById('birthDateInput');

birthDateInput.addEventListener('input', function(e) {
  // 移除所有非数字字符
  let inputValue = e.target.value.replace(/\D/g, '');
  let formattedValue = '';
  
  // 每2位数字后添加句号,最多处理8位数字(对应ddmmyyyy格式)
  for (let i = 0; i < inputValue.length; i++) {
    if (i !== 0 && i % 2 === 0) {
      formattedValue += '.';
    }
    formattedValue += inputValue[i];
    // 达到目标格式长度后停止处理
    if (formattedValue.length === 10) break;
  }
  
  // 修复光标位置异常问题
  const cursorPosition = e.target.selectionStart;
  e.target.value = formattedValue;
  // 若光标处于刚添加句号的位置,自动后移一位
  if (cursorPosition !== 0 && cursorPosition % 3 === 0) {
    e.target.setSelectionRange(cursorPosition + 1, cursorPosition + 1);
  } else {
    e.target.setSelectionRange(cursorPosition, cursorPosition);
  }
});

功能说明

  • 输入框限制最大长度为10,对应dd.mm.yyyy格式的字符数
  • 自动过滤非数字输入,确保用户只能输入有效日期数字
  • 输入第2、4位数字时自动添加句号,实时生成格式化结果
  • 优化光标位置,避免格式化操作导致光标跳转到末尾,提升输入体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:50:26