• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

用Javascript,html5限制用户表单只能输入未来月内日期

武飞扬头像
汤姆x
帮助1

今天开发遇到一个问题,限制用户表单只能输入未来一个月内的时间,查了不少资料,最后用了下面的方法:

1.首先表单用html5的input  type=date 格式,设置max和min值,也就是最大,最小日期范围,注意,这个日期格式必须是这样:2022-08-09;也就是说小于10必须补0 !

  1.  
    <body>
  2.  
     
  3.  
    <h3>只能输入未来30天以内的时间</h3>
  4.  
     
  5.  
    <input id="dateRange" type="date" min="2022-08-05" max="2022-09-04">
  6.  
     
  7.  
    </body>

2.用js动态生成min和max的日期:(用date函数setMonth,setDate对象也可以直接把月份或者天加上指定时间,并且到12月会自动转为明年一月,但是考虑到闰年等对2月天数影响,我决定用最保险的方法:取得当前时间戳,加上时间间隔的毫秒数,再转化为指定日期格式!)

  1.  
    <script>
  2.  
    var dateRange = document.querySelector("#dateRange");
  3.  
    var date_now = new Date().getTime();
  4.  
    var date_end = new Date(date_now 2592000000); //end时间戳加一个月毫秒数,并转化为日期格式
  5.  
    var date_now = new Date(date_now 43200000);//now时间戳设为12小时之后
  6.  
     
  7.  
    //输入date日期格式,转化为2022-08-22 格式的时间函数
  8.  
    function to_YY_MM_DD(date) {
  9.  
    let year = date.getFullYear();
  10.  
    let month = date.getMonth() 1;
  11.  
    let day = date.getDate();
  12.  
    //0
  13.  
    month = (month < 10) ? '0' month : month;
  14.  
    day = (day < 10) ? '0' day : day;
  15.  
    return year '-' month '-' day;
  16.  
     
  17.  
    }
  18.  
     
  19.  
    var max = to_YY_MM_DD(date_end);
  20.  
    var min = to_YY_MM_DD(date_now);
  21.  
     
  22.  
    dateRange.setAttribute("max", max);
  23.  
    dateRange.setAttribute("min", min);
  24.  
    </script>
学新通

3.最终效果,用户只能选择12小时后和30天内的日期:

学新通

 学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfface
系列文章
更多 icon
同类精品
更多 icon
继续加载