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

如何在React项目中设置HTML日期输入框为mm-yyyy格式(如07-2022)

在React中实现mm-yyyy格式的数字日期输入框

下面提供两种实用方案,适配你的React项目需求:

方案一:受控组件+自定义输入处理

这种方式完全可控,能精准限制输入格式、自动补充分隔符,并做格式校验。

实现代码

import { useState } from 'react';

const MonthYearInput = () => {
  const [dateValue, setDateValue] = useState('');
  const [error, setError] = useState('');

  const handleInputChange = (e) => {
    // 只保留输入中的数字
    let rawValue = e.target.value.replace(/\D/g, '');
    
    // 自动插入分隔符,当输入到第2位数字后添加'-'
    if (rawValue.length > 2) {
      rawValue = `${rawValue.slice(0, 2)}-${rawValue.slice(2, 6)}`;
    }
    
    // 限制输入总长度不超过7位(mm-yyyy)
    if (rawValue.length <= 7) {
      setDateValue(rawValue);
      setError('');
    }

    // 校验月份合法性
    if (rawValue.length >= 2) {
      const month = parseInt(rawValue.slice(0, 2), 10);
      if (month < 1 || month > 12) {
        setError('月份必须是01-12');
      }
    }
  };

  // 提交时的完整格式校验
  const handleSubmit = (e) => {
    e.preventDefault();
    const validFormat = /^(0[1-9]|1[0-2])-\d{4}$/.test(dateValue);
    if (!validFormat) {
      setError('请输入正确格式:mm-yyyy');
      return;
    }
    // 校验通过,执行后续逻辑
    console.log('有效日期:', dateValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={dateValue}
        onChange={handleInputChange}
        placeholder="mm-yyyy"
        style={{ padding: '8px', width: '120px' }}
      />
      {error && <p style={{ color: 'red', margin: '5px 0 0 0' }}>{error}</p>}
      <button type="submit" style={{ marginLeft: '10px' }}>提交</button>
    </form>
  );
};

export default MonthYearInput;

核心逻辑说明

  • 用replace(/\D/g, '')过滤掉所有非数字字符,确保输入仅为数字
  • 当输入长度超过2位时,自动插入-分隔月份和年份
  • 实时校验月份范围(01-12),提交时用正则校验完整格式
  • 受控组件模式保证输入值与状态完全同步

方案二:使用原生type="month"输入框

原生HTML提供了month类型的输入框,自带日期选择器(不同浏览器样式略有差异),能自动限制合法的月份和年份,只需转换格式即可得到mm-yyyy。

实现代码

import { useState } from 'react';

const NativeMonthYearInput = () => {
  const [formattedDate, setFormattedDate] = useState('');

  const handleMonthChange = (e) => {
    const rawValue = e.target.value;
    if (rawValue) {
      // 原生返回格式是yyyy-mm,转换为mm-yyyy
      const [year, month] = rawValue.split('-');
      setFormattedDate(`${month}-${year}`);
    } else {
      setFormattedDate('');
    }
  };

  return (
    <div>
      <input
        type="month"
        onChange={handleMonthChange}
        style={{ padding: '8px' }}
      />
      {formattedDate && <p>格式化后:{formattedDate}</p>}
    </div>
  );
};

export default NativeMonthYearInput;

优缺点

  • 优点:无需手动处理输入校验,自带选择器,用户体验友好
  • 缺点:浏览器样式不一致,无法完全自定义输入框的显示样式

内容的提问来源于stack exchange,提问作者Jabed H Tusar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:40:48